簡単 1件解決済み 正答率100.0%

Sum of Digits

Add up the decimal digits of a positive integer.

このチャレンジで学べること

  • Peel off the last digit with % 10 and drop it with // 10
  • Repeat a step until a number reaches zero
  • Keep a running total

問題

翻訳を表示

Add up every decimal digit of n. For 352 the digits are 3, 5 and 2.

Implement sum_of_digits(n).

Input

n: A positive integer.

Output

Return the sum of its digits.

制約

1 ≤ n ≤ 10¹⁸

例

例 1
入力:
n = 352

期待される出力:
expected = 10
入力:
long long n = 352;

期待される出力:
long long expected = 10;
入力:
long n = 352;

期待される出力:
long expected = 10;

解説

3 + 5 + 2 = 10.

例 2
入力:
n = 1000

期待される出力:
expected = 1
入力:
long long n = 1000;

期待される出力:
long long expected = 1;
入力:
long n = 1000;

期待される出力:
long expected = 1;

解説

1 + 0 + 0 + 0 = 1.

解き方のヒント

まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。

ヒント 1

Each step only needs the current last digit and the remaining prefix.

ヒント 2

Repeatedly peel off digits with division and remainder, or iterate through a string representation.

ヒント 3

Make sure single-digit inputs return that digit unchanged.

目安の計算量

O(d) time, O(1) extra space

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

# コーダー 言語 時間 メモリ AI 評価 解答
1 KKKaneki Ken Python 1,092 ms - 5/5 コードを見る

他の人の解答から学ぶ

コミュニティの解答

ネタバレ注意:下に1件の全解答あり まずは自分で挑戦してみましょう。他の開発者のコードやAIレビューも見ることができます。 サインインして課題を解くと議論に参加できます。