zoukankan      html  css  js  c++  java
  • LeetCode 202 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: 

    解法:

    1. 利用set保存每次计算的结果,若出现1,则返回true,若出现已有元素,而没有出现1则说明会陷入循环,返回false

    class Solution {
        public boolean isHappy(int n) {
            
            Set<Integer> set = new HashSet<>();
            int newn = 0;
            
            while(!set.contains(n))
            {
                set.add(n);
                newn = 0;
                while(n>0)
                {
                    newn += (n%10)*(n%10);
                    n /= 10;
                }
                if(newn==1) return true;
                
                n = newn;
            }
            
            return false;
            
        }
    }
    View Code

    2. 参考了discussion的做法,经规律总结,当计算结果在10以内时,只有7和1才会是happy number

    class Solution {
        public boolean isHappy(int n) {
            
            int newn = 0;
            
            while(n>9)
            {
                newn = 0;
                while(n>0)
                {
                    newn += (n%10)*(n%10);
                    n /= 10;
                }
                n = newn;
            }
            
            return n==7||n==1;
            
            
            
        }
    }
    View Code

    3. 由于计算结果最终会形成一个循环,可以参照Floyd判圈算法的思想,设置一个slow一次计算一步,一个fast一次计算两步,则当走入循环,fast会在一圈以内追上slow,使得两者此时指向的结果相同

    class Solution {
        public boolean isHappy(int n) {
            
            int slow = n;
            int fast = n;
            
            do{
                
                slow = helper(slow);
                fast = helper(helper(fast));
                
                if(slow==1||fast==1) return true;
                
            }while(slow!=fast);
            
            return false;
            
            
            
        }
        
        public int helper(int n)
        {
            int res = 0;
            while(n>0)
            {
                res += (n%10)*(n%10);
                n /= 10;
            }
            return res;
        }
    }
    View Code
  • 相关阅读:
    【CentOS】CentOS7开放及查看端口
    【nginx】配置https 证书生成的方法
    【MacOs】 Royal TSX SSH 和 FTP 中文乱码
    【PHP】thinkphp3.2.5
    【TCP/IP】入门学习笔记 五
    【TCP/IP】入门学习笔记 四
    HTTP
    【PHP】高并发和大流量的解决方案(思路)
    react多级路由 重定向与404定义
    react自定义导航组件 路由参数
  • 原文地址:https://www.cnblogs.com/trymorel/p/12622790.html
Copyright © 2011-2022 走看看