DEV Community

duccanhole
duccanhole

Posted on

code every day with me

--DAY 24--

Hi, I am going to make #100DaysOfCode Challenge. Everyday I will try solve 1 problem from leetcode or hackerrank. Hope you can go with me until end.
Now let's solve problem today:

  • Problem: Happy Number
  • Detail: here
  • Idea: After each step we split number, store new number to array, to check if number loops endlessly in a cycle, we need to check if array has any number appears twice or not.
    • Example: 2
    • step1: 2^2 = 4; array = [4];
    • step2: 4^2 = 16; array = [4,16];
    • step3: 1^2 + 6^2 = 37; array = [4,16,37];
    • step4: 3^2 + 7^2 = 58; array = [4,16,37,58];
    • step5: 5^2 + 8^2 = 89; array = [4,16,37,58,89];
    • step6: 8^2 + 9^2 = 145; array = [4,16,37,58,89,145];
    • step7: 1^2 + 4^2 + 5^2 = 42; array = [4,16,37,58,89,145,42];
    • step8: 4^2 + 2^2 = 20; array = [4,16,37,58,89,145,42,20];
    • step9: 2^2 + 0^2 = 4; array = [4,...,4];
    • Because number 4 appears twice, we return false.
  • My solution(javascript):
var Sum=(n)=>{
    let tmp=0;
    while(n>0){
        tmp=tmp+(n%10)**2;
        n=parseInt(n/10);
    }
    return tmp;
}
var isHappy = function(n) {
    let ans=[],i=1;
    ans[0]=n;
    while(i){
        let nums = Sum(ans[i-1]);
        if(nums==1) return true;
        else if(ans.includes(nums)) return false;
        ans.push(nums);
        i++;
    }
};
Enter fullscreen mode Exit fullscreen mode

-->If you have better solution or any question, please comment below. I will appreciate.

Discussion (0)