202. Happy Numbe

来源:互联网 发布:51单片机如何烧录程序 编辑:程序博客网 时间:2024/06/05 08:55

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

1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

这道题和 258.Add Dighits 的第一种解法很像,只不过上一道题的终止条件是小于10,而这道题的终止条件是无限循环(loops endlessly),也就是再循环过程中出现了以前出现的数字,所以这道题就简化成:判断是否出现过这个数字

通常采用的方法是:

  • 创建一个set或者hash_set函数,在这里我用的是CODEBLOCKS,如果用hash_set,会出现 error: 'hash_set' was not declared in this scope 的错误,VS2013上可以。

在这里我用的是set

#include <set>#include <iostream>using namespace std;    bool isHappy(int n) {        set<int> set;        while(n!=1){            int sum = 0;            while(n>0){                sum += (n % 10) * (n % 10);                n = n / 10;            }            if(set.find(sum) != set.end()) //循环终止条件            {                cout<<2<<endl;                return false;            }            else                {                    set.insert(sum);                }            n = sum;        }        cout<<1<<endl;        return true;    }int main(){    int n;    cin>>n;    isHappy(n);    return 0;}
  • 然后就是大神级别的方法了,在DISSCUS中看到如下方法,复杂度只有o(1)哦
int digitSquareSum(int n) {    int sum = 0, tmp;    while (n) {        tmp = n % 10;        sum += tmp * tmp;        n /= 10;    }    return sum;}bool isHappy(int n) {    int slow, fast;    slow = fast = n;    do {        slow = digitSquareSum(slow);        fast = digitSquareSum(fast);        fast = digitSquareSum(fast);    } while(slow != fast);    if (slow == 1) return 1;    else return 0;}
0 0
原创粉丝点击