0258. Add Digits (E)
Add Digits (E)
题目
Given a non-negative integer num
, repeatedly add all its digits until the result has only one digit.
Example:
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。Input: 38
Output: 2
Explanation: 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?
题意
将一个整数的各位数相加得到新整数,重复该步骤直到最终得到的是一个一位数。
思路
常规方法就是不断拆分相加直到得到最终结果。
O(1)方法:具体解析见LeetCode: Add Digits - 非负整数各位相加。
代码实现
Java
迭代
class Solution {
public int addDigits(int num) {
while (num > 9) {
num = solve(num);
}
return num;
}
private int solve(int num) {
int res = 0;
while (num != 0) {
res += num % 10;
num /= 10;
}
return res;
}
}
公式计算
class Solution {
public int addDigits(int num) {
return (num - 1) % 9 + 1;
}
}
JavaScript
迭代
/**
* @param {number} num
* @return {number}
*/
var addDigits = function (num) {
while (num > 9) {
let tmp = 0
while (num) {
tmp += num % 10
num = Math.trunc(num / 10)
}
num = tmp
}
return num
}
公式计算
/**
* @param {number} num
* @return {number}
*/
var addDigits = function (num) {
return (num - 1) % 9 + 1
}
更多精彩