Skip to content

add _66.java solution2 #116

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 25, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/main/java/com/fishercoder/solutions/_66.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,21 @@ public int[] plusOne(int[] digits) {
return newNumber;
}
}

public static class Solution2 {
public int[] plusOne(int[] digits) {
int len = digits.length;
for (int i = len - 1; i >= 0; i--) {
if (digits[i] == 9) {
digits[i] = 0;
} else {
digits[i]++;
return digits;
}
}
int[] newNumber = new int[len + 1];
newNumber[0] = 1;
return newNumber;
}
}
}
26 changes: 24 additions & 2 deletions src/test/java/com/fishercoder/_66Test.java
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
package com.fishercoder;

import com.fishercoder.solutions._66;
import static org.junit.Assert.assertArrayEquals;

import org.junit.BeforeClass;
import org.junit.Test;

import static org.junit.Assert.assertArrayEquals;
import com.fishercoder.solutions._66;

public class _66Test {
private static _66.Solution1 solution1;
private static _66.Solution2 solution2;
private static int[] digits;

@BeforeClass
public static void setup() {
solution1 = new _66.Solution1();
solution2 = new _66.Solution2();
}

@Test
Expand All @@ -32,4 +35,23 @@ public void test3() {
digits = new int[]{2, 4, 9, 3, 9};
assertArrayEquals(new int[]{2, 4, 9, 4, 0}, solution1.plusOne(digits));
}

@Test
public void test4() {
digits = new int[]{9, 9, 9, 9, 9};
assertArrayEquals(new int[]{1, 0, 0, 0, 0, 0}, solution2.plusOne(digits));
}

@Test
public void test5() {
digits = new int[]{8, 9, 9, 9, 9};
assertArrayEquals(new int[]{9, 0, 0, 0, 0}, solution2.plusOne(digits));
}

@Test
public void test6() {
digits = new int[]{2, 4, 9, 4, 9};
assertArrayEquals(new int[]{2, 4, 9, 5, 0}, solution2.plusOne(digits));
}

}