Happy Number
Square the digits of a number, add the squares, repeat, and decide whether the chain ever reaches 1.
Take a positive integer nnntruenfalse
Example 1
Output: true
Explanation: 1² + 9² = 82, 8² + 2² = 68, 6² + 8² = 100, 1² + 0² + 0² = 1.
Example 2
Output: false
Explanation: 2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4, and from there the same numbers repeat without reaching 1.
The Idea
Write 19 on a sheet of paper. Square each digit, 1 and 81, add them, and write the total, 82, underneath. Do the same to 82: 64 + 4 makes 68. Then 36 + 64 makes 100, and 1 + 0 + 0 makes 1. From 1 nothing changes any more, because 1² is 1. So 19 is happy.
Now start from 2. The steps give 4, then 16, 37, 58, 89, 145, 42 and 20. The digits of 20 give 4 + 0 = 4, a number we have already written. Look at the two rows of boxes in the picture: the top row, labelled "n = 19", ends in the teal box 1, and the bottom row, labelled "n = 2", bends back from 20 to 4.
Each number leads to one next number, so once 4 shows up a second time, the orange boxes from 4 to 20 repeat in the same order forever. Simply waiting for 1 would never end for 2. So the real question is: how do we know it is time to stop and answer false
Could a chain avoid both 1 and a repeat by growing bigger and bigger? No. A digit squared is at most 81, so a number with four digits leads to at most 4 × 81 = 324, which is smaller than the number. Larger numbers shrink even faster, and from any number below 1000 the next one is at most 243 (9² + 9² + 9²).
So every chain soon stays among a limited set of small numbers, and it must hit a number it has seen before. That leaves two endings. Either the chain reaches 1 and stays there, or it falls into a loop without 1, like the orange boxes. The answer is true
Solution Approach
The code needs three things: the next number from the digits, a way to notice the repeat, and a rule for reading the answer. The repeat can be noticed by remembering every number seen, or with two markers that move at different speeds.
Getting the next number
How do we pick out the digits of 145 one at a time? The remainder 145 % 10145 / 10
Can this sum get too big for an intintint
Remembering the numbers seen
What is the plainest way to notice a repeat? Put each number into a HashSet<Integer>
Two markers at different speeds
Can we notice the loop without storing anything? Imagine two markers walking along the bottom row of the picture. The marker named slowfastfastslow
For n = 2, slowfast
What if the chain reaches 1 instead? Then fastfastslow
Reading the answer
When should the walk stop? Either fastslowfastnfast
Java Solution
The method isHappy
- First, a helper method
returns the sum of the squares of the digits ofnext(n) . It starts a total,n , at 0. Then a loop takes the last digitsum withd , addsn % 10 tod * d , and drops the digit withsum , untiln /= 10 is 0.n - In
, the markerisHappy starts onslow and the markern onfast , one step ahead. If both started onnext(n) , they would count as meeting before either one had moved.n - A
loop runs as long aswhile is not 1 andfast is not equal toslow . Each pass movesfast one step withslow andnext(slow) two steps withfast .next(next(fast)) - After the loop, return
.fast == 1
The mainInteger.MAX_VALUE
public class HappyNumber {
public static boolean isHappy(int n) {
int slow = n;
int fast = next(n);
while (fast != 1 && slow != fast) {
slow = next(slow); // one step
fast = next(next(fast)); // two steps
}
return fast == 1;
}
// Sum of the squares of the digits of n.
static int next(int n) {
int sum = 0;
while (n > 0) {
int d = n % 10; // last digit
sum += d * d;
n /= 10; // drop the last digit
}
return sum;
}
public static void main(String[] args) {
int[] tests = {19, 2, 1, 7, 1111111, Integer.MAX_VALUE};
for (int n : tests) {
System.out.println("n = " + n + ": next = " + next(n) + ", happy = " + isHappy(n));
}
}
}
Running it prints:
n = 19: next = 82, happy = true
n = 2: next = 4, happy = false
n = 1: next = 1, happy = true
n = 7: next = 49, happy = true
n = 1111111: next = 7, happy = true
n = 2147483647: next = 260, happy = false
The line for 19 shows next = 82happy = truefalse
The line n = 1fastnext(1)true
Look at the last line: the largest int
Complexity
The cost is one digit walk for n
- Time: O(log n), because the first call of
visits each of the about log10 n digits ofnext , and every later number is at most 810. From such small numbers the markers meet or reach 1 within a fixed number of passes: at most 15 for every start below 1000, counted in a test run.n - Space: O(1), because the method keeps only
,slow ,fast andsum , while ad of seen numbers would store the whole chain.HashSet
The same one-step and two-step markers find a loop of nodes in