• LeetCode 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

    Credits:
    Special thanks to @mithmatt and @ts for adding this problem and creating all test cases.

    题目:让你判断一个数是否是开心数。一个正数,用它的数字的平方和来代替他,如果有结果等于1,则就是一个开心数。如果一个数一直无限循环还是得不到1,

    那么就不是开心数。

    这个题目要建立一个hash表,来判断是否无限循环。

    class Solution {
    public:
       
        bool isHappy(int n) {
            map<int, int> intMap;
            int sum;
            while(1)
            {
                sum = 0;
                while (n >= 10)
                {
                    sum += (n % 10)*(n % 10);
                    n = n / 10;
                }
                sum += n*n;
                if (1 == sum)return true;
                else n = sum;
                if (intMap.find(n) == intMap.end())
                    intMap[n] = 1;
                else break;
            }
            return false;
        }
    };
  • 相关阅读:
    文档API
    vi编辑器常用方法
    storm实战入门一
    redis教程
    为redis分配一个新的端口
    Lucene分页查询
    Lucene搜索方式大合集
    HBase Scan类用法
    java.util.Queue用法
    Makefile中预定义变量
  • 原文地址:https://www.cnblogs.com/csudanli/p/5343527.html
Copyright © 2020-2023  润新知