Skip to content

Instantly share code, notes, and snippets.

@walkingtospace
Created April 24, 2015 22:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save walkingtospace/5fa181ee4f83bd4201e4 to your computer and use it in GitHub Desktop.
Save walkingtospace/5fa181ee4f83bd4201e4 to your computer and use it in GitHub Desktop.
Happy number
/*
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