力扣:快乐数(7这个数字好奇怪呀)

class Solution {
    public boolean isHappy(int n) {
        
        while(true){
            int x1 = n;
            int sum=0;
        while(x1 > 0){
        x1 = n/10;
        int x2 = n%10;
        sum += x2 * x2;
        n = n/10;
        }

        n = sum;

         if(n==1)return true;
        if(n<10 & n!=7 )  break;
        }
        return false;
    }
}

上面是我写的代码,我很好奇,7这个数字好奇怪呀!

求解每一位的平方和的方法:

        while(n > 0){
            int digit = n % 10;
            sum += digit * digit;
            n /= 10;
        }

boolean判断的方式:

return slow == 1;

快慢指针的思想求解:(方法很好,很能体现快慢指针思想的精髓)



public class Solution {
    public int squareSum(int n) {
        int sum = 0;
        while(n > 0){
            int digit = n % 10;
            sum += digit * digit;
            n /= 10;
        }
        return sum;
    }

    public boolean isHappy(int n) {
        int slow = n, fast = squareSum(n);
        while (slow != fast){
            slow = squareSum(slow);
            fast = squareSum(squareSum(fast));
        };
        return slow == 1;
    }
}

 

代码随想录的卡尔用的是Set集合(哈希法)  我觉得也很好

用set集合去判断某个元素是否会重复的问题

  public boolean isHappy(int n) {
        Set<Integer> record = new HashSet<>();
        while (n != 1 && !record.contains(n)) {
            record.add(n);
            n = getNextNumber(n);
        }
        return n == 1;
    }

    private int getNextNumber(int n) {
        int res = 0;
        while (n > 0) {
            int temp = n % 10;
            res += temp * temp;
            n = n / 10;
        }
        return res;
    }

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值