Wednesday, April 22, 2015

202. Happy Number (easy)

Q:
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example: 
Input: 19
Output: true
Explanation: 
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
A:
就是用个Set来检查是否出现 endless loop。

class Solution {
public:
    bool isHappy(int n) {
        set<int> s;
        while(true)
        {
            int val = helper(n);
            if(val == 1)
            {
                return true;
            }
            if(s.find(val) != s.end()) // already found, 
                return false; 
            
            s.insert(val);            
            n = val;
        }
        return false;        
    }
private:
    int helper(int n)
    {
        int res = 0;
        while(n!=0)
        {
            int v = n %10;
            n /= 10;
            res += v*v;
        }
        return res;
    }
};


Mistakes:

又一次,栽在了while loop的条件上。



1 comment:

  1. Hi there! I simply want to give an enormous thumbs up for the great data you've here on this post. I shall be coming back to your blog for extra soon. online casino games

    ReplyDelete