• LeetCode(202): Happy Number


    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

    题意:对于任意一个整数如果将其各位平方相加,然后相加之和在进行各位平方相加,循环下去,如果最后之和为1,则是Happy Number返回True,否则程序可能从某个数开始陷入循环。

    思路:用一个数组保存已经计算出的结果,如果新的计算结果为1则返回True,如果不为1,且在数组中出现则返回False,否则将新的结果加入到数组中去,继续循环下去。

    代码:

    //获得n的个位数平方和 
    public int get_square_of_digits(int n){
            int result = 0;
            while(n>0){
                result = result + (n%10) * (n%10);
                n=n/10;
            }
            return result;
        }
        
     
     
        public boolean isHappy(int n) {
            if(n==0) return false;
            if(n==1) return true;
            List a= new ArrayList<Integer>();
                
            while(n!=1){
                    n = get_square_of_digits(n);
                    if(a.contains(n)){
                        return false;
                    }else{
                        a.add(n);
                    }
                }
                return true;
        }
  • 相关阅读:
    SQL 标准中的四种隔离级别
    java中快速排序的理解以及实例
    java中对插入排序的理解以及实例
    对冒泡排序的理解和实例
    MYSQL面试
    软件测试面试问题
    软件测试
    Linux常用命令
    关于将博客搬家至博客园的声明
    MFC常见问题以及解决方法(1)_MFC下文本编辑框按下回车后窗口退出
  • 原文地址:https://www.cnblogs.com/Lewisr/p/5125408.html
Copyright © 2020-2023  润新知