Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added happy_number.cpp #38

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions Famous-Coding-Interview-Problems/happy_number.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
* Detect if a number is a happy number. A number is happy number if
* sequence of operations where number is replaced by sum of square
* of its digits leads eventually to 1. A number is not a happy number
* if we are in an infinite loop when above operations are performed.
*
* Input: 49
* 4^2 + 9^2 = 16 + 81 = 97
* 9^2 + 7^2 = 81 + 49 = 130
* 1^2 + 3^2 + 0^2 = 1 + 9 + 0 = 10
* 1^2 + 0^2 = 1
* Thus 49 is a happy number.
* Approach:
*
* We can treat this problem same as finding a cycle in a linked list.
* Imagine intermediate numbers as node and operation of square and sum
* as link.
* If we find the cycle, and the cycle is at 1, number is a happy number.
* Else, the number is not a happy number.
*/

#include <iostream>

int square_sum(int num)
{
int squared_sum = 0;
while (num > 0) {
squared_sum += (num % 10) * (num % 10);
num /= 10;
}
return squared_sum;
}

bool is_happy(int num)
{
int slow = num;
int fast = num;

do {
slow = square_sum(slow);
fast = square_sum(square_sum(fast));
} while (slow != fast);
return slow == 1;
}

int main()
{
int num = 45;
if (is_happy(num)) {
std::cout << num << " is a happy number." << std::endl;
} else {
std::cout << num << " is not a happy number." << std::endl;
}
num = 49;
if (is_happy(num)) {
std::cout << num << " is a happy number." << std::endl;
} else {
std::cout << num << " is not a happy number." << std::endl;
}
return 0;
}