202. Happy Number
Asked at 25Google55Microsoft55Amazon52Bloomberg50Meta46Apple35Snowflake100Audible69BlackRock100Jump Trading100Nike100X94Swiggy82Airbnb66Autodesk59Accenture54Tesla52Cisco51Uber50Agoda48Visa48tcs46PayPal42Oracle27TikTok26
Problem
Repeatedly replace n by the sum of the squares of its digits. n is happy if this reaches 1; otherwise it loops forever in a cycle without 1. Decide whether n is happy.
Example: 19 → true (1 + 81 = 82 → 68 → 100 → 1); 2 → false
Repeatedly summing squared digits either reaches 1 or loops. Detect the loop with Floyd (or a seen-set).
Complexity: O(log n) per step; the sequence quickly drops below 243.
class Solution:
def isHappy(self, n: int) -> bool:
def nxt(x):
return sum(int(d) ** 2 for d in str(x))
slow, fast = n, nxt(n)
while fast != 1 and slow != fast:
slow, fast = nxt(slow), nxt(nxt(fast))
return fast == 1
assert Solution().isHappy(19) is True
assert Solution().isHappy(2) is False
class Solution {
public boolean isHappy(int n) {
int slow = n, fast = next(n);
while (fast != 1 && slow != fast) { slow = next(slow); fast = next(next(fast)); }
return fast == 1;
}
private int next(int x) {
int s = 0;
for (; x > 0; x /= 10) s += (x % 10) * (x % 10);
return s;
}
}
func isHappy(n int) bool {
next := func(x int) int { // sum of the squares of the digits
s := 0
for ; x > 0; x /= 10 {
s += (x % 10) * (x % 10)
}
return s
}
slow, fast := n, next(n) // Floyd: either reach 1 or loop
for fast != 1 && slow != fast {
slow, fast = next(slow), next(next(fast))
}
return fast == 1
}