File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ ## 题目
2
+
3
+ * 66 . 加一
4
+
5
+ 给定一个由 整数 组成的 非空 数组所表示的非负整数,在该数的基础上加一。
6
+
7
+ 最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。
8
+
9
+ 你可以假设除了整数 0 之外,这个整数不会以零开头。
10
+
11
+
12
+ ## 思路
13
+ 先从最后一位加1;
14
+ 若值比10大,则本位置仅保留个位上的数,进一位,倒数第二位上的数加1;
15
+ 若值比10小,则本位置上的数直接为该值;
16
+ 循环如上操作,若最终首位不为0,则说明最后一次计算,首位上没有进1,直接输出即可;
17
+ 若最终首位为0,则说明最后一次计算,首位上进行了进1,估需要在前面补充一个1。
18
+ (因为本题中只是末尾加1,所有只要有进位,也仅会出现进1的情况,即仅会有9加1本位保持0,向前一位进1。)
19
+
20
+ ## 代码
21
+
22
+ ``` php
23
+ class Solution {
24
+
25
+ /**
26
+ * @param Integer[] $digits
27
+ * @return Integer[]
28
+ */
29
+ function plusOne($digits) {
30
+ $length = sizeof($digits);
31
+ $ans = 0;
32
+ $add = 1;
33
+ for ($i = $length - 1; $i>=0; $i--) {
34
+ $temp = $digits[$i] + $add;
35
+ if ($temp >= 10) {
36
+ $digits[$i] = $temp - 10;
37
+ $add = 1;
38
+ } else {
39
+ $digits[$i] = $temp;
40
+ $add = 0;
41
+ }
42
+ }
43
+ if ($digits[0] == 0) {
44
+ return array_merge([1], $digits);
45
+ } else {
46
+ return $digits;
47
+ }
48
+
49
+ }
50
+ }
51
+ ```
You can’t perform that action at this time.
0 commit comments