码迷,mamicode.com
首页 > 移动开发 > 详细

202 Happy number

时间:2015-04-23 14:58:47      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

202 Happy number

Question

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
技术分享
技术分享
技术分享
技术分享

Idea

int型的数据有10位数字,最大的值即为技术分享,平方和为技术分享,所以个一个810大小的数组即可表示所以可能被计算出来的平方和。

给一个n值,先计算这个n的各位数的平方和,如果这个和以前出现过(m==n也算出现过),那么这个数就不是happy number。

原因:If a number is happy, then all members of its sequence are happy; if a number is unhappy, all members of the sequence are unhappy.
如果一个数是happy number,那么他的各位数字的顺序无论怎么颠倒,新的数仍然是happy number。同理,如果不是,无论怎么颠倒,也不是happy number。如果算出来的和以前算过,那么说明这一步是从那个和算过来的,现在从这个和再算的话,就又回去了,就是一个无限循环了。

Code

bool isHappy(int n) {
    bool hash[810] = {false};
    int m = n;
    while (1) {
        int sum = 0;
        while (m) {
            sum += (m % 10) * (m % 10);
            m /= 10;
        }
        if (sum == 1) return true;
        else if (hash[sum] || m == n) return false;
        hash[sum] = true;
        m = sum;
    }
    return false;
}

 

202 Happy number

标签:

原文地址:http://www.cnblogs.com/binarylu/p/4450225.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!