Happy Number 判断一个整数的各个位数的平方的和到最后是不是1

来源:互联网 发布:ie60和ie80知乎 编辑:程序博客网 时间:2024/05/22 07:08

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


//之所以用set,是因为貌似最后除了循环的情况之外,其余的和都能为1//String.valueOf和Integer.toString最后的结果都是一样的,可是看看Integer.toString就直到是把Integer转换为String的obJect返回
//而String.valueOf(x)是把x所属的类型转为String

//Integer.parseInt(String s)
@return     the integer value represented by the argument in decimal.


public class Solution {
    public boolean isHappy(int n) {
        Set<Integer> set=new HashSet<Integer>();
        int sum=0;
        while(n>1){
            if(set.add(n)==false) return false;
            sum=0;//认真搞清楚逻辑,不然真烦,这儿一定要置零
            while(n!=0){
                sum += Math.pow(n%10, 2);//注意这个函数的使用
                n=n/10;
            }
            n=sum;//把sum回传给n
        }
        return true;
    }
}


public class Solution {
    public boolean isHappy(int n) {
        Set<Integer> set=new HashSet<Integer>();
        int sum=0;
        while(n>1){
            String s=Integer.toString(n);
            //if(set.contains(sum)) return false;
            //else set.add(sum);
            if(set.add(sum)==false) return false;//上边两句可以被这句代替,多么简洁并体现了set的add特性:如果有重复,则add的时候返回false
            sum=0;
            for(int i=0;i<s.length();i++){
                int m=s.charAt(i)-'0';
                sum+=m*m;
            }
            n=sum;
        }
        return true;
    }
}

我觉得我写得够简洁了,直到看到了这个http://www.xgezhang.com/leetcode_happy_number.html

public class Solution {
    public boolean isHappy(int n) {
        Set<Integer> numberSet = new HashSet<Integer>();
          
        while (n!=1){
            if (numberSet.add(n)==false){
                return false;
            }
            //char[] chars = String.valueOf(n).toCharArray();
            //char[] chars = Integer.toString(n).toCharArray();
            char[] chars =(n+"").toCharArray();//这两句都可以
            int total = 0;
            //for (Character ch: chars){这两种写法都成立
            for (char ch: chars){
                total += Math.pow(Integer.parseInt(ch+""),2);//这儿必须写成ch+""变为String,因为Integer.parseInt(String s)
                //这个函数的返回是@return     the integer value represented by the argument in decimal.
            }
            n = total;
        }
        return true;
    }
}

0 0
原创粉丝点击