Accepted Cpp Solution using unordered_set


  • 0
    R
    bool isHappy(int n) {
    	if(0==n) return false;
    
    	int num=n; 
    	unordered_set<int> set;
    	while(true){
    		int val=0;
    		while(0!=num){
    			int p=num%10;
    			val+=p*p;
    			num/=10;
    		}
    		num=val;
    		if(1==num){
    			return true;
    		} else {
    			auto ret_pair=set.insert(num);
    			if(!ret_pair.second){
    				//cycle
    				return false;
    			}
    		}
    	}
    }
    

    this problem is too simple to explain.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.