LeetCode --- 202. Happy Number


LeetCode --- 202. Happy Number | mkyforever
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number

1^2 + 9^2 = 82  8^2 + 2^2 = 68  6^2 + 8^2 = 100  1^2 + 0^2 + 0^2 = 1  
这道题的要求是判断一个数是不是"happy"的。关于"happy"数字的定义:从这个数字(正整数)开始,用其各个数位上数字的平方和替换这个数字,直到等于1或者出现重复。如果最后等于1说明是"happy"数组。
简单模拟,用Hash记录出现过的数组,用以判断是否出现环。
时间复杂度:O(n)
空间复杂度:O(n)

use hash map to keep all the previous calculated number, if it is loop, exist with false, otherwise it will become 1.
  1. public boolean isHappy(int n) {  
  2.     Set<Integer> set = new HashSet<>();  
  3.     while(set.add(n)) {  
  4.         n = sumSquares(n);  
  5.         if(n == 1return true;  
  6.     }  
  7.     return false;  
  8. }  
  9.   
  10. private int sumSquares(int n) {  
  11.     int sum = 0;  
  12.     while(n != 0) {  
  13.         int digit = n % 10;  
  14.         sum += digit * digit;  
  15.         n /= 10;  
  16.     }  
  17.     return sum;  
  18. }  
https://leetcode.com/discuss/77996/simple-and-short-solution-in-java
public boolean isHappy(int n) { if (n <= 0) return false; HashSet<Integer> set = new HashSet<Integer>(); while(n !=1 && !set.contains(n)) { set.add(n); int m = n; n = 0; while(m != 0) { n += (m%10)*(m%10); m = m/10; } } if (n == 1) return true; else return false; }
http://rosettacode.org/wiki/Happy_numbers#Java
   public static boolean happy(long number){
       long m = 0;
       int digit = 0;
       HashSet<Long> cycle = new HashSet<Long>();
       while(number != 1 && cycle.add(number)){
           m = 0;
           while(number > 0){
               digit = (int)(number % 10);
               m += digit*digit;
               number /= 10;
           }
           number = m;
       }
       return number == 1;
   }
https://sisijava.wordpress.com/
   public boolean isHappy(int n) {
        HashSet<Integer> happy = new HashSet<Integer>();
        int sum = 0;
        while(!happy.contains(n)){
            sum =0;
            happy.add(n);
            int tmp = 0;
            while(n > 0){
                tmp = n % 10;
                n = n / 10;
                sum = sum + tmp*tmp;
            }
            if(sum == 1){
                return true;
            }
            n = sum;
        }
        return false;
    }
https://github.com/checkcheckzz/coding-questions/blob/master/problem/Happy%20Number.cpp

http://blog.csdn.net/yuanhisn/article/details/46118297
happy number is defined by the following process. Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers. Display an example of your output here.

If n is not happy, then its sequence does not go to 1. Instead, it ends in the cycle:



4, 16, 37, 58, 89, 145, 42, 20, 4, ...

To see this fact, first note that if n has m digits, then the sum of the squares of its digits is at most 9^2 m, or 81m.
For m=4 and above,



n\geq10^{m-1}>81m

so any number over 1000 gets smaller under this process and in particular becomes a number with strictly fewer digits. Once we are under 1000, the number for which the sum of squares of digits is largest is 999, and the result is 3 times 81, that is, 243.
  • In the range 100 to 243, the number 199 produces the largest next value, of 163.
  • In the range 100 to 163, the number 159 produces the largest next value, of 107.
  • In the range 100 to 107, the number 107 produces the largest next value, of 50.
Considering more precisely the intervals [244,999], [164,243], [108,163] and [100,107], we see that every number above 99 gets strictly smaller under this process. Thus, no matter what number we start with, we eventually drop below 100. An exhaustive search then shows that every number in the interval [1,99] either is happy or goes to the above cycle.
The above work produces the interesting result that no positive integer other than 1 is the sum of the squares of its own digits, since any such number would be a fixed point of the described process.
http://www.jiuzhang.com/solutions/happy-number/
    private int getNextHappy(int n) {
        int sum = 0;
        while (n != 0) {
            sum += (n % 10) * (n % 10);
            n /= 10;
        }
        return sum;
    }
    
    public boolean isHappy(int n) {
        HashSet<Integer> hash = new HashSet<Integer>();
        while (n != 1) {
            if (hash.contains(n)) {
                return false;
            }
            hash.add(n);
            n = getNextHappy(n);
        }
        return true;
    }
https://leetcode.com/discuss/59684/beat-easy-understand-java-solution-with-brief-explanation
public boolean isHappy(int n) { Set<Integer> inLoop = new HashSet<Integer>(); int squareSum,remain; while (inLoop.add(n)) { squareSum = 0; while (n > 0) { remain = n%10; squareSum += remain*remain; n /= 10; } if (squareSum == 1) return true; else n = squareSum; } return false; }

X. O(1) Space
good idea. one thing I wanna point out is that the space complexity of hashset impl is low(it's bounded).
https://leetcode.com/discuss/33349/o-1-space-java-solution
public boolean isHappy(int n) { int x = n; int y = n; while(x>1){ x = cal(x) ; if(x==1) return true ; y = cal(cal(y)); if(y==1) return true ; if(x==y) return false; } return true ; } public int cal(int n){ int x = n; int s = 0; while(x>0){ s = s+(x%10)*(x%10); x = x/10; } return s ; }
https://leetcode.com/discuss/32842/use-the-same-way-as-checking-cycles-in-a-linked-list
bool isHappy(int n) { int A = nxt(n), B = nxt(nxt(n)); while (A != 1 && A != B) { A = nxt(A); B = nxt(B); B = nxt(B); } return A == 1; } private: int nxt(int num) { int res = 0; while (num) { res += (num % 10) * (num % 10); num /= 10; } return res; }
X. Proof
https://leetcode.com/discuss/71625/explanation-those-posted-algorithms-mathematically-valid
First of all, it is easy to argue that starting from a number I, if some value - say a - appears again during the process after k steps, the initial number I cannot be a happy number. Because a will continuously become a after every k steps.
Therefore, as long as we can show that there is a loop after running the process continuously, the number is not a happy number.
There is another detail not clarified yet: For any non-happy number, will it definitely end up with a loop during the process? This is important, because it is possible for a non-happy number to follow the process endlessly while having no loop.
To show that a non-happy number will definitely generate a loop, we only need to show that for any non-happy number, all outcomes during the process are bounded by some large but finite integer N. If all outcomes can only be in a finite set (2,N], and since there are infinitely many outcomes for a non-happy number, there has to be at least one duplicate, meaning a loop!
Suppose after a couple of processes, we end up with a large outcome O1 with D digits whereD is kind of large, say D>=4, i.e., O1 > 999 (If we cannot even reach such a large outcome, it means all outcomes are bounded by 999 ==> loop exists). We can easily see that after processing O1, the new outcome O2 can be at most 9^2*D < 100D, meaning that O2 can have at most 2+d(D) digits, where d(D) is the number of digits D have. It is obvious that2+d(D) < D. We can further argue that O1 is the maximum (or boundary) of all outcomes afterwards. This can be shown by contradictory: Suppose after some steps, we reach another large number O3 > O1. This means we process on some number W <= 999 that yields O3. However, this cannot happen because the outcome of W can be at most 9^2*3 < 300 < O1.
Done.
for those who are less patient, here is some findings,
(1) for a positive integer n, n is either a happy number or unhappy with cycle length 7.
(2) digitSquareSum(n) < n for all n>99
(3) there are 19 happy numbers and 80 unhappy numbers in [1,99]
(4) happyNumLess100 = [1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97]
(5) for these numbers the corresponding update count to become 1 is stepcnt = [0, 5, 1, 2, 4, 3, 3, 2, 3, 4, 4, 2, 5, 3, 3, 2, 4, 4, 3]

let g(n) denote digitSquareSum function, eg. g(4) = g(16), g(19) = 82 etc

  • for nin [1,10), g(n)>=n, since g(n)=n*n>=nwith equality hold only for n=1
  • for other n with only highest digit nonzero (eg. 10, 90, 500, 4000, 20000, etc), g(n)<n
  • and we can factor n into sum of numbers with only highest digit nonzero, eg. 12045 = 10000 + 2000 + 40 + 5
in this way, we can show for any n>=100, g(n) < n
by calculate all cases in [1,200],
L1 = [digitSquareSum(n) - n for n in range(1,200)]
L2 = list(filter(lambda x: x>0, L1))
L3 = list(filter(lambda x: x>0, L1[99:]))
len(L1), len(L2), len(L3)
>>> (199, 50, 0)
max(L2), L1.count(max(L2)), 1 + L1.index(max(L2))
>>> (72, 1, 9)
min(L2), L1.count(min(L2)), 1 + L1.index(min(L2))
>>> (2, 1, 2)

the test shows that

(1) for all n>=100, g(n) < n.
(2) there are only 50 number such that g(n) < n, among them for g(n)-n
(3) the unique largest is 9 (g(9)-9 = 72), the unique smallest is 2 (g(2) - 2 = 2).

which shows a surprising result, there is only two cases for any positive integer n

(1) n is a happy number
(2) n is not happy and have cycle length 7 (we will further verify about the cycle length soon)
this can be verified like below. the algorithm is basically
Algorithm 1
input: n (positive integer)
func g = digitSquareSum
while n!=1 and n's current value not appeared in this calculation process
    n= g(n)
output: True if n==1, false otherwise

but we have showed,

(1) for all n>=100, the update step (n= g(n)) reduce the value of n
(2) a loop exist if and only if update have both decreasing and increasing effect in the whole process (the only case of equality is 1, which is excluded at first)
(3) increasing update can only happen for 50 numbers, all of them less than 100
so if we have a True table for all numbers less than 100 indicating happiness, denote it as HappyTable, then algorithm could be changed to
Algorithm 2
input: n (positive integer)
func g = digitSquareSum
while n>99
    n = g(n)
output: HappyTable(n)
if we use function isHappy previously showed (return 0 if n is happy otherwise return the smallet cycle length)
mylist = [isHappy(n) for n in range(1,100)]
happyList = [i+1 for i, val in enumerate(mylist) if val==0]
unhappyList = [i+1 for i, val in enumerate(mylist) if val!=0] # or equivalently if val==7
len(mylist), len(happyList), len(unhappyList)
>>> (99, 19, 80)
happyList
>>> [1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97]

http://www.chenguanghe.com/happy-number/
http://www.geeksforgeeks.org/happy-number/
A number will not be a Happy Number when it makes a loop in its sequence that is it touches a number in sequence which already been touched. So to check whether a number is happy or not, we can keep a set, if same number occurs again we flag result as not happy. 

We can solve this problem without using extra space and that technique can be used in some other similar problem also. If we treat every number as a node and replacement by square sum digit as a link, then this problem is same as finding a loop in a linklist :


So as proposed solution from above link, we will keep two number slow and fast both initialize from given number, slow is replaced one step at a time and fast is replaced two steps at a time. If they meet at 1, then the given number is Happy Number otherwise not.
int numSquareSum(int n)
{
    int squareSum = 0;
    while (n)
    {
        squareSum += (n % 10) * (n % 10);
        n /= 10;
    }
    return squareSum;
}
 
//  method return true if n is Happy number
bool isHappynumber(int n)
{
    int slow, fast;
 
    //  initialize slow and fast by n
    slow = fast = n;
    do
    {
        //  move slow number by one iteration
        slow = numSquareSum(slow);
 
        //  move fast number by two iteration
        fast = numSquareSum(numSquareSum(fast));
 
    }
    while (slow != fast);
 
    //  if both number meet at 1, then return true
    return (slow == 1);
}

https://github.com/kaushal02/CP/blob/master/Self-topics/Happy%20numbers.cc
Read full article from LeetCode --- 202. Happy Number | mkyforever

Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts