202. Happy Number

来源:互联网 发布:网络编辑部简介 编辑:程序博客网 时间:2024/06/06 03:45

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

思路:就是循环到n<10为止,在这过程中,把n拆分运算

代码如下(已通过leetcode)

public class Solution {
   public boolean isHappy(int n) {
    List<Integer> list=new ArrayList<Integer>();
    list.add(n);
    int temp=n;
    boolean isrepeate=false;
       while(temp>0) {
        if(isrepeate) break;
        String strn=""+temp;
        temp=0;
        int length=strn.length();
        for(int i=0;i<length;i++) {
        temp+=(strn.charAt(i)-'0')*(strn.charAt(i)-'0');
        }
        Iterator<Integer> it=list.iterator();
        while(it.hasNext()) {
        if(temp==it.next()) {
        if(temp==1) return true;
        else {
        isrepeate=true;
        break;
        }
       
        }
        if(!isrepeate) list.add(temp);
       
       }
       return false;
   }
}

0 0
原创粉丝点击