- Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path0258-add-digits.rb
42 lines (34 loc) · 755 Bytes
/
0258-add-digits.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# frozen_string_literal: true
# 258. Add Digits
# https://leetcode.com/problems/add-digits
# Easy
=begin
Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.
Example 1:
Input: num = 38
Output: 2
Explanation: The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only one digit, return it.
Example 2:
Input: num = 0
Output: 0
Constraints:
0 <= num <= 231 - 1
=end
# @param {Integer} num
# @return {Integer}
defadd_digits(num)
num == 0 ? 0 : (num - 1) % 9 + 1
end
# **************** #
# TEST #
# **************** #
require"test/unit"
classTest_add_digits < Test::Unit::TestCase
deftest_
assert_equal2,add_digits(38)
assert_equal0,add_digits(0)
end
end