258. Add Digits

本文探讨了如何求解数字根问题,即不断累加一个非负整数的所有位数直到结果仅剩一位数的过程。提供了两种高效算法,一种利用公式1+(num-1)%9直接计算结果,另一种通过判断num%9的余数来得出答案。

题目描述:

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?

思路一:

数字根问题:https://en.wikipedia.org/wiki/Digital_root#Congruence_formula


class Solution {
    public int addDigits(int num) {
        return 1 + (num - 1) % 9;
    }
}
思路二:

class Solution {
    public int addDigits(int num) {
        return num % 9 == 0 ? (num == 0 ? 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
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值