轉眼過了 10 天,堅持了 1/3 的鐵人賽
好幾度想放棄,還有許多事情要忙(專題、複習、研究文件、架網站等)
即便刷比較簡單的題目,也需要花一小時以上刷題、TDD、上傳、寫文章等
多希望自己體質是一天只要睡 2-3 小時 (離題遠了
Coderwars 題目已經刷到有點膩
即便如此,也要刷起來
目標是挑戰在 5 分鐘左右完成影片
這次 6 分鐘 3 題
題目(Summing a number's digits):
1
2
3
4
5Write a function named sumDigits which takes a number as input and returns the sum of the absolute value of each of the number's decimal digits. For example:
sumDigits 10 # Returns 1
sumDigits 99 # Returns 18
sumDigits -32 # Returns 5
Let's assume that all numbers in the input will be integer values.
1
2
3
4
5
6def sumDigits(number)
end
Test.assert_equals(sumDigits(10), 1)
Test.assert_equals(sumDigits(99), 18)
Test.assert_equals(sumDigits(-32), 5)
題目(Sum of two lowest positive integers):
1
2
3
4
5Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 positive integers. No floats or non-positive integers will be passed.
For example, when an array is passed like [19, 5, 42, 2, 77], the output should be 7.
[10, 343445353, 3453445, 3453545353453] should return 3453455.
1
2
3
4
5
6
7def sum_two_smallest_numbers(numbers)
#Your code here
end
Test.assert_equals(sum_two_smallest_numbers([5, 8, 12, 18, 22]), 13)
Test.assert_equals(sum_two_smallest_numbers([7, 15, 12, 18, 22]), 19)
Test.assert_equals(sum_two_smallest_numbers([25, 42, 12, 18, 22]), 30)
1
2
3
4
5
6
7
8
9You are given an odd-length array of integers, in which all of them are the same, except for one single number.
Complete the method which accepts such an array, and returns that single different number.
The input array will always be valid! (odd-length >= 3)
Examples
[1, 1, 2] ==> 2
[17, 17, 3, 17, 17, 17, 17] ==> 3
1
2
3
4
5
6
7def stray (numbers)
end
Test.describe("Example test cases") do
Test.assert_equals(stray([1, 1, 2]), 2)
end
影片解題:
答案:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16# Summing a number's digits
def sumDigits(number)
number.to_s.chars.map{|x| x.to_i}.sum
end
# Sum of two lowest positive integers
def sum_two_smallest_numbers(numbers)
numbers.sort[0..1].sum
end
# Find the stray number
def stray (numbers)
numbers.select{|x| numbers.count(x) == 1}.join.to_i
end
本文同步發布於 小菜的 Blog https://riverye.com/