LeetCode Happy Number

本文介绍了一种用于判断“快乐数”的算法实现,并提供了两种不同的解决方案。一种是使用HashSet存储历史求和结果避免重复循环,另一种则采用快慢指针的方法寻找循环节点。这两种方法都有效地解决了LeetCode上的快乐数问题。

原题链接在这里:https://leetcode.com/problems/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

题解:

用HashSet 存储过往的和,若是遇见了相同的和,则表示出现了无限循环,没有happy number.

Note: 1.  Math.pow()的argument 和 return value 都是 double 型,返回时要注意cast.

遍历一个数字的每一位就用下面的代码:

1 while(n!=0){
2     int digit = n%10;
3     n = n/10;
4 }

AC Java:

public class Solution {
    public boolean isHappy(int n) {
        HashSet<Integer> hs = new HashSet<Integer>();
        
        while(!hs.contains(n)){
            if(n == 1){
                return true;
            }
            hs.add(n);
            
            int sum = 0;
            while(n != 0){
                int digit = n%10;
                n = n/10;
                sum += (int)Math.pow(digit,2);
            }
            n = sum;
        }
        return false;
    }
}

节省空间可以不需要HashSet<Integer> hs 来记录过往的digit square sum. 

可以类似Linked List Cycle用快慢指针找到loop的出口, 若出来时walker 和 runner 都是1就是happy number.

AC Java:

 1 class Solution {
 2     public boolean isHappy(int n) {
 3         if(n <= 0){
 4             throw new IllegalArgumentException("Input number is not positive.");
 5         }
 6         
 7         int walker = n;
 8         int runner = n;
 9         do{
10             walker = sumOfDigitSqure(walker);
11             runner = sumOfDigitSqure(runner);
12             runner = sumOfDigitSqure(runner);
13         }while(walker != runner);
14         
15         if(walker == 1){
16             return true;
17         }else{
18             return false;
19         }
20     }
21     
22     private int sumOfDigitSqure(int n){
23         int sum = 0;
24         
25         while(n != 0){
26             int digit = n%10;
27             n /= 10;
28             sum += digit*digit;
29         }
30         
31         return sum;
32     }
33 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/4825059.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值