Interview 150

Happy Number

Problem
LC 202
File
interview150_LC202HappyNumber.java
Path
pkg5leetcode/interview150/interview150_LC202HappyNumber.java
Package
pkg5leetcode.interview150
Command
java pkg5leetcode/interview150/interview150_LC202HappyNumber.java
Approach
Floyd cycle detection on sum-of-squares sequence.
Complexity
Time O(log n), Space O(1)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/interview150/interview150_LC202HappyNumber.java
1package pkg5leetcode.interview150;2 3/*4 * Happy Number | LC 2025 * APPROACH: Floyd cycle detection on sum-of-squares sequence.6 * COMPLEXITY: Time O(log n), Space O(1)7 */8public class interview150_LC202HappyNumber {9    static int next(int n) {10        int sum = 0;11        while (n > 0) {12            int d = n % 10;13            sum += d * d;14            n /= 10;15        }16        return sum;17    }18 19    static boolean isHappy(int n) {20        int slow = n, fast = next(n);21        while (fast != 1 && slow != fast) {22            slow = next(slow);23            fast = next(next(fast));24        }25        return fast == 1;26    }27 28    public static void main(String[] args) {29        check(isHappy(19), "case1");30        check(!isHappy(2), "case2");31        System.out.println("all tests passed");32    }33 34    static void check(boolean cond, String name) {35        if (!cond) throw new AssertionError("FAILED: " + name);36        System.out.println("  PASS " + name);37    }38}