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

Armstrong Number

Check whether a number equals the sum of its digits raised to the digit count.

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

  • Count the digits of a number
  • Raise each digit to the digit count and add them up
  • Compare the result with the original number

โจทย์

ดูฉบับแปล

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¹⁸

ตัวอย่าง

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

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

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

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

คำอธิบาย

1³ + 5³ + 3³ = 1 + 125 + 27 = 153.

ตัวอย่างที่ 2
อินพุต:
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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

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

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

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