zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    树的遍历
    字符串转化到实数
    redis笔记_源码_跳表skiplist
    《parsing techniques》中文翻译和正则引擎解析技术入门
    sublime3 Package Control和 中文安装
    python基础——字典dict
    python基础1
    pandas入门总结1
    numpy入门总结2
    numpy入门总结1
  • 原文地址:https://www.cnblogs.com/csudanli/p/5343527.html
Copyright © 2011-2022 走看看