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
  • 相关阅读:
    API学习
    某社区的常用免费图床 free image hosting websites,如何用Ruby与Perl启动浏览器, 打开指定网页
    Delphi7下SuperObject的JSON使用方法
    Delphi中使用ISuperObject解析Json数据
    Delphi 数据存储到oracle数据库TBLOB/TCLOB的方法 包括JSON串的解析
    Delphi7 JSON的读取和拼接
    SQL查看所有表大小的语句
    ora12541监听程序无法识别连接
    oracle新建用户类问题
    Delphi版本插值Lagrange
  • 原文地址:https://www.cnblogs.com/trymorel/p/12622790.html
Copyright © 2011-2022 走看看