ง่าย 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Harshad Number

Check whether a number is divisible by the sum of its digits (a Harshad or Niven number).

สิ่งที่คุณจะได้เรียนรู้

  • Compute a digit sum with a loop
  • Use the remainder operator to test divisibility
  • Keep the original value while consuming digits

โจทย์

ดูฉบับแปล

A Harshad number (also called a Niven number) is a positive integer that is divisible by the sum of its own digits. For example, 18 has digit sum 1 + 8 = 9, and 18 ÷ 9 = 2 with no remainder, so 18 is a Harshad number.

Implement harshad_number(n).

Input

n: The number to test.

Output

Return true if n is divisible by the sum of its decimal digits, otherwise false.

เงื่อนไข

1 ≤ n ≤ 10^18

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
n = 156

ผลลัพธ์ที่คาดหวัง:
expected = True
อินพุต:
long long n = 156;

ผลลัพธ์ที่คาดหวัง:
bool expected = true;
อินพุต:
long n = 156;

ผลลัพธ์ที่คาดหวัง:
bool expected = true;

คำอธิบาย

The digit sum is 1 + 5 + 6 = 12, and 156 = 12 × 13, so the answer is true.

ตัวอย่างที่ 2
อินพุต:
n = 19

ผลลัพธ์ที่คาดหวัง:
expected = False
อินพุต:
long long n = 19;

ผลลัพธ์ที่คาดหวัง:
bool expected = false;
อินพุต:
long n = 19;

ผลลัพธ์ที่คาดหวัง:
bool expected = false;

คำอธิบาย

The digit sum is 1 + 9 = 10, and 19 is not a multiple of 10, so the answer is false.

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 1

Add up the digits first, using a copy of n.

คำใบ้ 2

n is Harshad when the remainder of n divided by the digit sum is 0.

คำใบ้ 3

The digit sum of a positive number is never 0, so the division is safe.

ความซับซ้อนที่คาดหวัง

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

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

คำตอบที่ผ่านดีที่สุดของแต่ละคน คำตอบที่เร็วกว่า ใช้หน่วยความจำน้อยกว่า และได้คะแนนดีกว่าจะอยู่ด้านบน

ยังไม่มีคำตอบที่ผ่าน แก้โจทย์นี้แล้วคว้าอันดับหนึ่งไปเลย

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก