Sfoglia il codice sorgente

#feat:leetcode p66题题解

yangyi 2 settimane fa
parent
commit
6fc38fc1c6
2 ha cambiato i file con 75 aggiunte e 0 eliminazioni
  1. 34 0
      src/leetcode/p66/Solution.java
  2. 41 0
      src/leetcode/p66/SolutionTest.java

+ 34 - 0
src/leetcode/p66/Solution.java

@@ -0,0 +1,34 @@
+package leetcode.p66;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: Solution
+ * @Author: 杨逸
+ * @Data:2026/3/11 21:09
+ * @Description: https://leetcode.cn/problems/plus-one/description/
+ *66. 加一
+ */
+public class Solution {
+    public int[] plusOne(int[] digits) {
+        int flag = 1;
+        int index = digits.length-1;
+        while (flag != 0 && index >= 0){
+            int temp = digits[index] +flag;
+            if (temp == 10) {
+                digits[index] = 0;
+                flag = 1;
+            }else{
+                digits[index] = temp;
+                flag = 0;
+            }
+            index--;
+        }
+        if (flag == 1){
+            int[] res = new int[digits.length+1];
+            res[0] = 1;
+            System.arraycopy(digits,0,res,1,digits.length);
+            return res;
+        }
+        return digits;
+    }
+}

+ 41 - 0
src/leetcode/p66/SolutionTest.java

@@ -0,0 +1,41 @@
+package leetcode.p66;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+import static org.junit.Assert.assertArrayEquals;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: SolutionTest
+ * @Author: 杨逸
+ * @Data:2026/3/11 21:09
+ * @Description:
+ */
+@RunWith(Parameterized.class)
+public class SolutionTest {
+    public static final Solution solution = new Solution();
+    private int[] digits;
+    private int[] expected;
+    public SolutionTest(int[] digits, int[] expected){
+        this.digits = digits;
+        this.expected = expected;
+    }
+    @Parameterized.Parameters
+    public static Collection<Object[]> data(){
+        return Arrays.asList(new Object[][]{
+                {new int[]{1,2,3},new int[]{1,2,4}},
+                {new int[]{4,3,2,1},new int[]{4,3,2,2}},
+                {new int[]{9},new int[]{1,0}},
+        });
+    }
+
+    @Test
+    public void plusOne() {
+        assertArrayEquals(expected,solution.plusOne(digits));
+    }
+}