LoginSignup
0
0

More than 3 years have passed since last update.

【アルゴリズム】桁の足し算

Posted at

問題説明

自然数Nを受け取って、Nの各桁の足し算を行いreturnするsolutionメソッドを作成してください。
例)N=123の場合、1 + 2 + 3 = 6をreturn。

条件

  • Nの範囲:100,000,000以下の自然数

入出力の例

N answer
123 6
987 24

解説

※解説は私が作成したコードなので、もっといいアルゴリズム等々ありましたら、共有してください!


public class Solution {
    public int solution(int n) {
        // 合計を保存用
        int sum = 0;
        while(n > 0) {
            sum += n % 10; // 10で割り算して余りを足していく。
            n /= 10;  // 10で割り算した結果を次の計算に使うためnに代入。
        }

        return sum;
    }
}
0
0
2

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