LeetCode #202: Happy Number | Facebook Interview Question | C++

preview_player
Показать описание
**** Best Books For Data Structures & Algorithms for Interviews:**********
*****************************************************************************

Happy Number (Leetcode 202)
Facebook Coding Interview - Happy Number

#Amazon #Facebook #CodingInterview #LeetCode #SingleNumber #Google
Рекомендации по теме
Комментарии
Автор

Nice video..I love your channel
I have one question: in your second approach why did you put fast_sum = sum_of_squares(n) before the loop. shouldn't fast_sum and slow_sum start at the same position before the loop?

ayyubshaffy
Автор

Wow so it's so much faster to simply use more times the sum_of_squares with the second solution, than to search an unordered_set with the already visited unhappy numbers

georgederleres
Автор

What if there is a loop but the loop is very long and the fast sum overlaps the slow sum repeatedly without both stopping at the same number? I am just confused on how you can be sure if there is a loop the fast sum will always get to the same point as the slow sum?

dhruvshah
Автор

wy u take ?? it is two step ahead of slow sum??

anushsharma
Автор

my solution - 0.0ms

bool isHappy(int n) {
int res=n;
for(int i=0;i<10;i++)
{
int sum=0;
n=res;
while(n!=0)
{
int p=n%10;
sum=sum+p*p;
n=n/10;
}
res=sum;
if(res==1)
return true;
}
return false;
}

kapiljetwani
Автор

class Solution {
public:
bool isHappy(int n)
{
set<int>s;
int val=0;

while(1)
{
int sum=0;
while(n)
{
val=n%10;
sum=sum+val*val;
n=n/10;
}
if(sum==1)
{
return true;
}
if(s.find(sum)!=s.end())
{
return false;
}
s.insert(sum);
n=sum;
}

}
};

wecan
visit shbcf.ru