258:各位相加

This commit is contained in:
轩辕龙儿 2022-03-03 21:21:57 +08:00
parent 29a23593dd
commit 3e67072a6c
2 changed files with 93 additions and 0 deletions

View 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)
}

View File

@ -0,0 +1,33 @@
<p>给定一个非负整数 <code>num</code>,反复将各个位上的数字相加,直到结果为一位数。返回这个结果。</p>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> num =<strong> </strong><code>38</code>
<strong>输出:</strong> 2
<strong>解释: </strong>各位相加的过程为<strong>
</strong>38 --&gt; 3 + 8 --&gt; 11
11 --&gt; 1 + 1 --&gt; 2
由于&nbsp;<code>2</code> 是一位数,所以返回 2。
</pre>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> num =<strong> </strong>0
<strong>输出:</strong> 0</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>0 &lt;= num &lt;= 2<sup>31</sup>&nbsp;- 1</code></li>
</ul>
<p>&nbsp;</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>