Happy Number

来源:互联网 发布:广州海度网络是培训吗 编辑:程序博客网 时间:2024/06/03 15:34

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
快乐数(happy number)有以下的特性:在给定的进位制下,该数字所有数位(digits)的平方和,得到的新数再次求所有数位的平方和,如此重复进行,最终结果必为1。
以十进位为例:
2 8 → 2²+8²=68 → 6²+8²=100 → 1²+0²+0²=1
3 2 → 3²+2²=13 → 1²+3²=10 → 1²+0²=1
3 7 → 3²+7²=58 → 5²+8²=89 → 8²+9²=145 → 1²+4²+5²=42 → 4²+2²=20 → 2²+0²=4 → 4²=16 → 1²+6²=37……
因此28和32是快乐数,而在37的计算过程中,37重覆出现,继续计算的结果只会是上述数字的循环,不会出现1,因此37不是快乐数。
不是快乐数的数称为不快乐数(unhappy number),所有不快乐数的数位平方和计算,最後都会进入 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 的循环中。
在十进位下,100以内的快乐数有(OEIS中的数列A00770) :1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100。


代码:
class Solution {public:  bool isHappy(int n) {    if(n < 1){      return false;    }    if(n == 1){      return true;    }    set<int> temp;    temp.insert(n);    while(true){      int sum = 0;      while(n != 0){         int Digital = n % 10;         n = n / 10;         sum = sum + Digital * Digital;      }      if(sum == 1){        return true;      }      else      {        if(temp.find(sum) == temp.end()){          temp.insert(sum);        }else{          return false;        }      }      n = sum;    }  }};

其他:
class Solution {public:    bool isHappy(int n) {        if (n < 1)            return false;        if (n == 1)            return true;        unordered_set<int> showedNums;        showedNums.insert(n);        while(true)        {            int s = 0;            while(n)            {                s += (n % 10) * (n % 10);                n = n / 10;            }            if (s == 1)                return true;            else if (showedNums.find(s) != showedNums.end())                return false;            n = s;            showedNums.insert(s);        }    }};

#include<iostream>#include<vector>#include<algorithm>#include<set>using namespace std;bool judge(int num);int main(){int data[] = { 1, 2, 3, 44, 5, 6, 7, 8, 9, 10, 11 };for (int i = 0; i < sizeof(data) / sizeof(data[0]); i++){cout << judge(data[i]) << endl;}system("pause");return 0;}bool judge(int num){if (num == 0)return false;if (num == 1)return true;set<int> temp;temp.insert(num);bool index = true;while (index){int s = 0;while (num){s += pow(num % 10, 2);num = num / 10;}if (s == 1){index = false;return true;}else if (temp.find(s) != temp.end()){index= false;return false;}num = s;temp.insert(s);}}


0 0
原创粉丝点击