258. Add Digits

本文介绍了一种将非负整数不断累加其各个位上的数字直至结果仅剩一位数的算法。通过两种方法实现:一种使用循环,另一种则采用数学公式在O(1)时间内解决。此外,还探讨了如何避免使用循环或递归。

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 = 111 + 1 = 2. Since 2 has only one digit, return it.


class Solution {
public:
    int addDigits(int num) {
        
        int ans = 0;
        while(num/10 != 0)
        {
            ans += num % 10;
            num /= 10;
            if(num/10 == 0)
            {
                ans += num;
                num = ans;
                ans = 0;
            }
        }
        return num;
    }
};

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

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


class Solution {
public:
    int addDigits(int num) {
        return num==0?0:(num%9==0?9:(num%9));
     }
};



/** * 大整数拆分 * @param num 一个大整数 * @return 分治后的两个局部大整数 */ public static testBigInteger[] splitNumber(testBigInteger num) { int n = num.digits.length; int mid = n/2; int[] low = Arrays.copyOfRange(num.digits,0,mid); int[] high = Arrays.copyOfRange(num.digits,mid,n); testBigInteger lowpart = new testBigInteger(low,false); testBigInteger highpart = new testBigInteger(high,false); return new testBigInteger[]{lowpart,highpart}; } /** * Karatsuba算法 * @param other 另一个大整数 * @return 乘法得到的结果 */ public testBigInteger karatsubamultiply(testBigInteger other){ if (this.digits.length <= 2 && other.digits.length <= 2) { return this.multipy(other); } testBigInteger[] p1 = splitNumber(this); testBigInteger p1Low = p1[0]; testBigInteger p1High = p1[1]; testBigInteger[] p2 = splitNumber(other); testBigInteger p2Low = p2[0]; testBigInteger p2High = p2[1]; testBigInteger z1 = p1High.karatsubamultiply(p2High); testBigInteger z2 = p1Low.karatsubamultiply(p2Low); testBigInteger z3 = (p1High.add(p1Low)).karatsubamultiply(p2High.add(p2Low)); testBigInteger middle = z3.subtract(z2).subtract(z1); int n =this.digits.length; int m =n/2; testBigInteger result = z1.shiftLeft(2*m).add(middle.shiftLeft(m)).add(z2); result.isNegative = this.isNegative != other.isNegative; if (result.isZero()) result.isNegative = false; return result; } /** * 左移操作 * @param m 进位的多少 * @return 返回数组*10^m次方后的结果 */ public testBigInteger shiftLeft(int m) { if(m==0) return this; int[] newDigits = new int[this.digits.length+m] ; System.arraycopy(this.digits,0,newDigits,0,this.digits.length); return new testBigInteger(newDigits,false);} 计算结果不对怎么办
最新发布
12-01
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值