Add Digits (E)
題目
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
Example:
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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/10637.html
標籤:其他
上一篇:CF 1383AString Transformation 1
下一篇:交換排序演算法之冒泡排序
