Skip to content

Commit 325a0e3

Browse files
realDuYuanChaogithub-actions
andauthored
leetcode-2021.3.27 (examplehub#88)
* convert-binary-number-in-a-linked-list-to-integer * Formatted with Google Java Formatter Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
1 parent 4fef756 commit 325a0e3

2 files changed

Lines changed: 43 additions & 0 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.examplehub.leetcode.easy;
2+
3+
import com.examplehub.leetcode.ListNode;
4+
5+
/*
6+
* https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/
7+
*/
8+
public class ConvertBinaryNumberInALinkedListToInteger {
9+
10+
public static int solution1(ListNode head) {
11+
StringBuilder builder = new StringBuilder();
12+
while (head != null) {
13+
builder.append(head.val);
14+
head = head.next;
15+
}
16+
return Integer.parseInt(builder.toString(), 2);
17+
}
18+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.examplehub.leetcode.easy;
2+
3+
import static org.junit.jupiter.api.Assertions.*;
4+
5+
import com.examplehub.leetcode.ListNode;
6+
import org.junit.jupiter.api.Test;
7+
8+
class ConvertBinaryNumberInALinkedListToIntegerTest {
9+
@Test
10+
void testSolution1() {
11+
ListNode head = new ListNode(1);
12+
ListNode node2 = new ListNode(0);
13+
ListNode node3 = new ListNode(1);
14+
head.next = node2;
15+
node2.next = node3;
16+
17+
assertEquals(ConvertBinaryNumberInALinkedListToInteger.solution1(head), 5);
18+
19+
head = new ListNode(1);
20+
assertEquals(ConvertBinaryNumberInALinkedListToInteger.solution1(head), 1);
21+
22+
head = new ListNode(0);
23+
assertEquals(ConvertBinaryNumberInALinkedListToInteger.solution1(head), 0);
24+
}
25+
}

0 commit comments

Comments
 (0)