zoukankan      html  css  js  c++  java
  • 19.Happy Number-Leetcode

    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,故用一个map来保存状态,暂未发现直接判断的方法

    #define IMAX numeric_limits<int>::max()
    class Solution {
    public:
        bool isHappy(int n) {
            if(n<=0)return false;
            map<int,int> vis;
            //int num = pow(10,9);
            while(n!=1)
            {
               // num++;
                //if(num==IMAX)break;
                if(vis.count(n))return false;//出现重复的中间数
                vis[n]=1;
                vector<int> vs;
                while(n)
                {
                    vs.push_back(n%10);
                    n=n/10;
                }
                n=0;
                for(int i=0;i<vs.size();++i)n=n+vs[i]*vs[i];
            }
            return true;
        }
    };
  • 相关阅读:
    final
    职场语句
    故事
    三个关键字
    关于重读字母去掉的代码
    Java书
    docker私库harbor的搭建
    配置允许匿名用户登录访问vsftpd服务,进行文档的上传下载、文档的新建删除等操作
    docker容器内外相互拷贝数据
    docker
  • 原文地址:https://www.cnblogs.com/freeopen/p/5482982.html
Copyright © 2011-2022 走看看