0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rubyアルゴリズム(Add Digits)

Last updated at Posted at 2021-05-22

問題

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

Follow up: Could you do it without any loop/recursion in O(1) runtime?

私の回答

def add_digits(num)
    int = num.digits.sum
    while int.to_s.length >= 2 do
        int = int.digits.sum
    end
    p int
end

number = gets.to_i
add_digits(number)

RunCodeして出力される答えはあっているのに、赤字で「Wrong Answer」も一緒に表示される。何故だ…

やったこと

int = num.digits.sum

これについては、まず配列にして桁ごとに切り分けて

38.digits # => [3, 8]

足した。シンプル。

[3, 8].sum # => 11

そして桁数が一桁になるまでwhileで分解→足し算を繰り返してみた。

    while int.to_s.length >= 2 do
        int = int.digits.sum
    end

でもWrong Answerらしい!!
動かしてみる限りあっていそうなのに。何故?

 

ここから追記

解決しました

結論:インプット値の取得とかいらなかった

LeetCodeの仕組みをよくわかってなかったですが、最後の

number = gets.to_i
add_digits(number)

ここがいらなかったです。
AtCoderとはまた違うんですね。

最終的な回答

def add_digits(num)
    int = num.digits.sum
    while int.to_s.length >= 2 do
        int = int.digits.sum
    end
    return int
end

pをreturnにし、無事Acceptedになりました。

0
0
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?