258:各位相加
This commit is contained in:
parent
29a23593dd
commit
3e67072a6c
60
src/main/java/leetcode/editor/cn/AddDigits.java
Normal file
60
src/main/java/leetcode/editor/cn/AddDigits.java
Normal file
@ -0,0 +1,60 @@
|
||||
//给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。返回这个结果。
|
||||
//
|
||||
//
|
||||
//
|
||||
// 示例 1:
|
||||
//
|
||||
//
|
||||
//输入: num = 38
|
||||
//输出: 2
|
||||
//解释: 各位相加的过程为:
|
||||
//38 --> 3 + 8 --> 11
|
||||
//11 --> 1 + 1 --> 2
|
||||
//由于 2 是一位数,所以返回 2。
|
||||
//
|
||||
//
|
||||
// 示例 1:
|
||||
//
|
||||
//
|
||||
//输入: num = 0
|
||||
//输出: 0
|
||||
//
|
||||
//
|
||||
//
|
||||
// 提示:
|
||||
//
|
||||
//
|
||||
// 0 <= num <= 2³¹ - 1
|
||||
//
|
||||
//
|
||||
//
|
||||
//
|
||||
// 进阶:你可以不使用循环或者递归,在 O(1) 时间复杂度内解决这个问题吗?
|
||||
// Related Topics 数学 数论 模拟 👍 475 👎 0
|
||||
|
||||
package leetcode.editor.cn;
|
||||
|
||||
//258:各位相加
|
||||
public class AddDigits {
|
||||
public static void main(String[] args) {
|
||||
Solution solution = new AddDigits().new Solution();
|
||||
solution.addDigits(38);
|
||||
}
|
||||
|
||||
//leetcode submit region begin(Prohibit modification and deletion)
|
||||
class Solution {
|
||||
public int addDigits(int num) {
|
||||
while (num >= 10) {
|
||||
int sum = 0;
|
||||
while (num >= 10) {
|
||||
sum += num % 10;
|
||||
num /= 10;
|
||||
}
|
||||
num += sum;
|
||||
}
|
||||
return num;
|
||||
}
|
||||
}
|
||||
//leetcode submit region end(Prohibit modification and deletion)
|
||||
}
|
||||
|
33
src/main/java/leetcode/editor/cn/doc/content/AddDigits.md
Normal file
33
src/main/java/leetcode/editor/cn/doc/content/AddDigits.md
Normal file
@ -0,0 +1,33 @@
|
||||
<p>给定一个非负整数 <code>num</code>,反复将各个位上的数字相加,直到结果为一位数。返回这个结果。</p>
|
||||
|
||||
<p> </p>
|
||||
|
||||
<p><strong>示例 1:</strong></p>
|
||||
|
||||
<pre>
|
||||
<strong>输入:</strong> num =<strong> </strong><code>38</code>
|
||||
<strong>输出:</strong> 2
|
||||
<strong>解释: </strong>各位相加的过程为<strong>:
|
||||
</strong>38 --> 3 + 8 --> 11
|
||||
11 --> 1 + 1 --> 2
|
||||
由于 <code>2</code> 是一位数,所以返回 2。
|
||||
</pre>
|
||||
|
||||
<p><strong>示例 1:</strong></p>
|
||||
|
||||
<pre>
|
||||
<strong>输入:</strong> num =<strong> </strong>0
|
||||
<strong>输出:</strong> 0</pre>
|
||||
|
||||
<p> </p>
|
||||
|
||||
<p><strong>提示:</strong></p>
|
||||
|
||||
<ul>
|
||||
<li><code>0 <= num <= 2<sup>31</sup> - 1</code></li>
|
||||
</ul>
|
||||
|
||||
<p> </p>
|
||||
|
||||
<p><strong>进阶:</strong>你可以不使用循环或者递归,在 <code>O(1)</code> 时间复杂度内解决这个问题吗?</p>
|
||||
<div><div>Related Topics</div><div><li>数学</li><li>数论</li><li>模拟</li></div></div><br><div><li>👍 475</li><li>👎 0</li></div>
|
Loading…
Reference in New Issue
Block a user