diff --git a/src/main/java/com/fishercoder/solutions/_1290.java b/src/main/java/com/fishercoder/solutions/_1290.java index 6840f00738..8e3c6c55a5 100644 --- a/src/main/java/com/fishercoder/solutions/_1290.java +++ b/src/main/java/com/fishercoder/solutions/_1290.java @@ -13,4 +13,15 @@ public int getDecimalValue(ListNode head) { return Integer.parseInt(sb.toString(), 2); } } + public static class Solution2 { + public int getDecimalValue(ListNode head) { + int sum = 0; + while (head != null) { + sum *= 2; + sum += head.val; + head = head.next; + } + return sum; + } + } } diff --git a/src/test/java/com/fishercoder/_1290Test.java b/src/test/java/com/fishercoder/_1290Test.java index 7023d9ec73..fb2878a21f 100644 --- a/src/test/java/com/fishercoder/_1290Test.java +++ b/src/test/java/com/fishercoder/_1290Test.java @@ -11,11 +11,13 @@ public class _1290Test { private static _1290.Solution1 solution1; + private static _1290.Solution2 solution2; private static ListNode head; @BeforeClass public static void setup() { solution1 = new _1290.Solution1(); + solution2 = new _1290.Solution2(); } @Test @@ -23,5 +25,9 @@ public void test1() { head = ListNode.createSinglyLinkedList(Arrays.asList(1, 0, 1)); assertEquals(5, solution1.getDecimalValue(head)); } - + @Test + public void test2() { + head = ListNode.createSinglyLinkedList(Arrays.asList(1, 1, 1)); + assertEquals(7, solution2.getDecimalValue(head)); + } } \ No newline at end of file