[LeetCode]258. Add Digits&202. Happy Number

本文介绍了两种数字操作算法:一种是将一个非负整数的所有位数相加直至结果为一位数;另一种是判断一个数是否为快乐数,即通过反复平方并求和其各位数字,看最终是否能归结为1。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

258 . Add Digits
Easy

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

For example:

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

4ms:

 public int addDigits(int num) {
        char[] cabin = Integer.valueOf(num).toString().toCharArray();
         while(cabin.length>1){
             int sum=0;
             for(char x:cabin){
                 sum+=x-'0';
             }
             cabin = Integer.valueOf(sum).toString().toCharArray();
         }

         return cabin[0]-'0';
    }

2ms:

 public int addDigits(int num) {
        num--;
         while(num>=9){
             num %=9;
         }
         return ++num;
    }

2ms:

 public int addDigits(int num) {
       return (num - 1) % 9 + 1;
    }

202 . Happy Number
Easy

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

1*1 + 9*9 = 82
8*8 + 2*2 = 68
6*6 + 8*8 = 100
1*1 + 0*0 + 0*0 = 1

8ms:

 public boolean isHappy(int n) {
        Set<Integer> se = new HashSet<Integer>();

        while(n!=1){
            n = getH(n);
            if(se.contains(n))
                return false;
            se.add(n);
        }
        return true;
    }
    private int getH(int n){
        int c = 0;
        while(n!=0){
            c+=(n%10)*(n%10);
            n /= 10;
        }
        return c;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值