Created
April 24, 2015 22:20
-
-
Save walkingtospace/5fa181ee4f83bd4201e4 to your computer and use it in GitHub Desktop.
Happy number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
https://leetcode.com/problems/happy-number/ | |
For cycle detection: | |
1. Floyd's tortoise and rabbit algorithm (two pointers; slow and fast) | |
2. Brant's algorithm | |
3. using Hash table to detect duplicated values; | |
*/ | |
class Solution { | |
public: | |
bool isHappy(int n) { | |
int slow = n, fast = n; | |
do { | |
slow = sumSquare(slow); | |
fast = sumSquare(sumSquare(fast)); | |
} while(slow != fast); | |
if(slow == 1) { | |
return true; | |
} | |
return false; | |
} | |
int sumSquare(int n) { | |
int sum = 0; | |
while(n) { | |
int temp = n % 10; | |
sum += temp*temp; | |
n /= 10; | |
} | |
return sum; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment