66:加一

This commit is contained in:
huangge1199@hotmail.com 2021-04-27 20:43:01 +08:00
parent 9ac7a23583
commit 3b3f6de496
2 changed files with 115 additions and 0 deletions

View File

@ -0,0 +1,75 @@
//给定一个由 整数 组成的 非空 数组所表示的非负整数在该数的基础上加一
//
// 最高位数字存放在数组的首位 数组中每个元素只存储单个数字
//
// 你可以假设除了整数 0 之外这个整数不会以零开头
//
//
//
// 示例 1
//
//
//输入digits = [1,2,3]
//输出[1,2,4]
//解释输入数组表示数字 123
//
//
// 示例 2
//
//
//输入digits = [4,3,2,1]
//输出[4,3,2,2]
//解释输入数组表示数字 4321
//
//
// 示例 3
//
//
//输入digits = [0]
//输出[1]
//
//
//
//
// 提示
//
//
// 1 <= digits.length <= 100
// 0 <= digits[i] <= 9
//
// Related Topics 数组
// 👍 682 👎 0
package leetcode.editor.cn;
//66:加一
public class PlusOne {
public static void main(String[] args) {
//测试代码
Solution solution = new PlusOne().new Solution();
System.out.println(solution.plusOne(new int[]{9}));
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int[] plusOne(int[] digits) {
for (int i = digits.length - 1; i >= 0; i--) {
digits[i] += 1;
if (digits[i] == 10) {
if (i == 0) {
digits = new int[digits.length + 1];
digits[0] = 1;
} else {
digits[i] %= 10;
}
} else {
break;
}
}
return digits;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,40 @@
<p>给定一个由 <strong>整数 </strong>组成的<strong> 非空</strong> 数组所表示的非负整数,在该数的基础上加一。</p>
<p>最高位数字存放在数组的首位, 数组中每个元素只存储<strong>单个</strong>数字。</p>
<p>你可以假设除了整数 0 之外,这个整数不会以零开头。</p>
<p> </p>
<p><strong>示例 1</strong></p>
<pre>
<strong>输入:</strong>digits = [1,2,3]
<strong>输出:</strong>[1,2,4]
<strong>解释:</strong>输入数组表示数字 123。
</pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入:</strong>digits = [4,3,2,1]
<strong>输出:</strong>[4,3,2,2]
<strong>解释:</strong>输入数组表示数字 4321。
</pre>
<p><strong>示例 3</strong></p>
<pre>
<strong>输入:</strong>digits = [0]
<strong>输出:</strong>[1]
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= digits.length <= 100</code></li>
<li><code>0 <= digits[i] <= 9</code></li>
</ul>
<div><div>Related Topics</div><div><li>数组</li></div></div>\n<div><li>👍 682</li><li>👎 0</li></div>