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

Happy Number

Decide whether repeatedly summing the squares of the digits of a number reaches 1.

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

  • Compute the sum of squared digits
  • Detect a repeating sequence with a set or two pointers
  • Stop a loop on either of two conditions

โจทย์

ดูฉบับแปล

Start with a positive integer and replace it by the sum of the squares of its digits. Keep doing that. If the number eventually becomes 1, the starting number is happy. Otherwise the process falls into a loop that never contains 1, and the number is unhappy. For example, 7 → 49 → 97 → 130 → 10 → 1, so 7 is happy.

Implement happy_number(n).

You need a way to notice that the sequence has started repeating, so the loop stops on unhappy numbers too.

Input

n: The starting number.

Output

Return true if the process reaches 1, otherwise false. The number 1 itself is happy.

เงื่อนไข

1 ≤ n ≤ 10^9

ตัวอย่าง

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

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

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

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

คำอธิบาย

1² + 9² = 82, then 8² + 2² = 68, then 6² + 8² = 100, then 1² + 0² + 0² = 1, so 19 is happy: true.

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

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

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

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

คำอธิบาย

4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 repeats without ever reaching 1, so the answer is false.

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

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

คำใบ้ 1

Write a helper that maps a number to the sum of the squares of its digits.

คำใบ้ 2

An unhappy number repeats a value it has already produced; remember the values you have seen.

คำใบ้ 3

The sequence drops below a few hundred very quickly, so the set stays small.

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

O(log n) steps per number, O(1) extra space with two pointers

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

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

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

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

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

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

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