ง่าย 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

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 ได้ เข้าสู่ระบบและแก้โจทย์เพื่อร่วมพูดคุย