Loading...
Loading...
Start with a number, replace it by the sum of the squares of its digits, and repeat. If you reach 1, the number is happy (19 → 82 → 68 → 100 → 1). Otherwise the process loops forever without reaching 1 (2 → 4 → 16 → 37 → … → 4).
Count the happy numbers from L to R. Write static int squareDigitSum(int n) and static boolean isHappy(int n). With no arrays to remember the values seen, detect the loop with a slow number that moves one step at a time and a fast number that moves two steps: if they meet at a value other than 1, the number is not happy.
Example 1
Input
1 10
Output
3
The happy numbers are 1, 7 and 10.
Example 2
Input
2 6
Output
0
None of 2, 3, 4, 5, 6 is happy.
Try the problem first. Open one hint at a time.
squareDigitSum: take each digit with % 10, add its square, drop it with / 10.
In isHappy, start slow = n and fast = squareDigitSum(n). Loop while fast != 1 && slow != fast.
Inside the loop move slow one step and fast two steps. After the loop, the number is happy exactly when fast == 1.
Once the fast number enters a loop, the slow one is caught within a few rounds, so the check always ends.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor