leetCode 202. Happy Number 哈希
202. Happy Number
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:19 is a happy number
12+ 92= 82
82+ 22= 68
62+ 82= 100
12+ 02+ 02= 1
思路:
采用set来判断容器中是否有该元素出现过,如果出现过,那么就形成了环状,结果返回false。否则找到快乐数字。返回true。
代码如下:
classSolution{public:boolisHappy(intn){set<int>myset;inttotal=0;while(n!=1){while(n){total+=(n%10)*(n%10);n/=10;}if(total==1)returntrue;if(myset.find(total)!=myset.end())returnfalse;elsemyset.insert(total);n=total;total=0;}returntrue;}};
关于set容器的使用练习。
2016-08-13 13:49:32
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。