Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8bd4f9b

Browse files
convert ll into int
1 parent 2cefc2f commit 8bd4f9b

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package codechallenge.easy.linkedlist;
2+
3+
import me.premaseem.myLib.MySLLNode;
4+
import org.junit.Test;
5+
6+
public class ConvertLinkedListToNumber {
7+
// Test Driven Development by Aseem Jain
8+
@Test
9+
public void test() {
10+
11+
int[] n = new int[] { 6, 3, 4, 8, 2 };
12+
MySLLNode ll = new MySLLNode(n);
13+
assert 63482 == solution1(ll);
14+
assert 63482 == solution2(ll);
15+
16+
}
17+
18+
// Basic solution
19+
private int solution1(MySLLNode ll) {
20+
String ans = "";
21+
while(ll != null){
22+
ans += ll.data;
23+
ll= ll.next;
24+
}
25+
return Integer.parseInt(ans);
26+
}
27+
28+
private int solution2(MySLLNode head) {
29+
int len=0;
30+
31+
MySLLNode ll = head;
32+
while(ll != null){
33+
len++;
34+
ll= ll.next;
35+
}
36+
37+
ll = head;
38+
int ans = 0;
39+
len--;
40+
while(ll != null){
41+
int n = (int) Math.pow(10,len--);
42+
ans += n * ll.data;
43+
ll= ll.next;
44+
}
45+
46+
return ans;
47+
}
48+
49+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /