diff --git a/src/main/java/com/fishercoder/solutions/_369.java b/src/main/java/com/fishercoder/solutions/_369.java index 189aa81a2a..8549a0f689 100644 --- a/src/main/java/com/fishercoder/solutions/_369.java +++ b/src/main/java/com/fishercoder/solutions/_369.java @@ -55,4 +55,33 @@ public ListNode plusOne(ListNode head) { } } + public static class Solution2 { + + public ListNode plusOne(ListNode head) { + ListNode dummyNode = new ListNode(0); + dummyNode.next = head; + + ListNode notNineNode = dummyNode; + + // find the right most node value != 9 + while (head != null) { + if (head.val != 9) { + notNineNode = head; + } + head = head.next; + } + + // increase the rightmost node value to 1 + notNineNode.val ++; + notNineNode = notNineNode.next; + + // set all the following node values with 9 to 0 + while (notNineNode != null) { + notNineNode.val = 0; + notNineNode = notNineNode.next; + } + return dummyNode.val != 0 ? dummyNode : dummyNode.next; + } + } + } diff --git a/src/test/java/com/fishercoder/_369Test.java b/src/test/java/com/fishercoder/_369Test.java new file mode 100644 index 0000000000..3f467e700d --- /dev/null +++ b/src/test/java/com/fishercoder/_369Test.java @@ -0,0 +1,29 @@ +package com.fishercoder; + +import com.fishercoder.common.classes.ListNode; +import com.fishercoder.common.utils.LinkedListUtils; +import com.fishercoder.solutions._203; +import com.fishercoder.solutions._369; +import org.junit.BeforeClass; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class _369Test { + + private static _369.Solution2 solution2; + private static ListNode head; + private static ListNode expected; + + @BeforeClass + public static void setup() { + solution2 = new _369.Solution2(); + } + + @Test + public void test1() { + head = LinkedListUtils.contructLinkedList(new int[]{1, 2, 9}); + expected = LinkedListUtils.contructLinkedList(new int[]{1, 3, 0}); + assertEquals(expected, solution2.plusOne(head)); + } +}