โจทย์
A number with k digits is an Armstrong number if the sum of each digit raised to the power k equals the number. For example 153 = 1³ + 5³ + 3³.
Implement is_armstrong(n).
Input
n: A non-negative integer.
Output
Return true if n is an Armstrong number.
เงื่อนไข
0 ≤ n ≤ 10¹⁸
ตัวอย่าง
อินพุต:
n = 153
ผลลัพธ์ที่คาดหวัง:
expected = True
อินพุต:
long long n = 153;
ผลลัพธ์ที่คาดหวัง:
bool expected = true;
อินพุต:
long n = 153;
ผลลัพธ์ที่คาดหวัง:
bool expected = true;
คำอธิบาย
1³ + 5³ + 3³ = 1 + 125 + 27 = 153.
อินพุต:
n = 10
ผลลัพธ์ที่คาดหวัง:
expected = False
อินพุต:
long long n = 10;
ผลลัพธ์ที่คาดหวัง:
bool expected = false;
อินพุต:
long n = 10;
ผลลัพธ์ที่คาดหวัง:
bool expected = false;
คำอธิบาย
1² + 0² = 1, which is not 10.
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
Count how many digits the number has before summing powers.
คำใบ้ 2
Compare the original number with the sum of each digit raised to that digit count.
คำใบ้ 3
Remember that 0 is a special one-digit case.
ความซับซ้อนที่คาดหวัง
O(k) time, O(1) extra space
แหล่งอ้างอิง
โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน