Dễ 0 đã giải Tỷ lệ chấp nhận 0%

Happy Number

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

Bạn sẽ học được gì

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

Đề bài

Xem bản dịch

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.

Ràng buộc

1 ≤ n ≤ 10^9

Ví dụ

Ví dụ 1
Đầu vào:
n = 19

Kết quả mong đợi:
expected = True
Đầu vào:
long long n = 19;

Kết quả mong đợi:
bool expected = true;
Đầu vào:
long n = 19;

Kết quả mong đợi:
bool expected = true;

Giải thích

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

Ví dụ 2
Đầu vào:
n = 4

Kết quả mong đợi:
expected = False
Đầu vào:
long long n = 4;

Kết quả mong đợi:
bool expected = false;
Đầu vào:
long n = 4;

Kết quả mong đợi:
bool expected = false;

Giải thích

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

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

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

Gợi ý 2

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

Gợi ý 3

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

Độ phức tạp mong đợi

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

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Lời giải đạt tốt nhất của mỗi người. Lời giải nhanh hơn, tốn ít bộ nhớ hơn và được đánh giá cao hơn sẽ đứng trên.

Chưa có lời giải nào đạt. Giải bài này để giành hạng nhất.

Học hỏi từ người khác

Giải pháp cộng đồng

Chưa có giải pháp nào được chia sẻ. Hãy giải thử thách này để đăng giải pháp đầu tiên.