-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdd_Two_Numbers.kt
More file actions
46 lines (41 loc) · 1.14 KB
/
Add_Two_Numbers.kt
File metadata and controls
46 lines (41 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package Add_Two_Numbers
import structure.ListNode
import java.math.BigInteger
import java.util.*
/**
* Merge each list node to [String], then covert to [BigInteger], then add, then covert to [ListNode]
*
* This is BAD solution, consider using [Stack]
*/
class Solution {
companion object {
fun getString(l1: ListNode?): String {
return if (l1 != null) {
"${getString(l1.next)}${l1.`val`}"
} else {
""
}
}
}
fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {
val num1 = getString(l1)
val num2 = getString(l2)
val sum = (num1.toBigInteger() + num2.toBigInteger()).toString()
var node: ListNode? = null
sum.reversed().forEach {
if (node == null) {
node = ListNode(it.toString().toInt())
} else {
push(node!!, it.toString().toInt())
}
}
return node
}
private fun push(l1: ListNode, a: Int) {
if (l1.next == null) {
l1.next = ListNode(a)
} else {
push(l1.next!!, a)
}
}
}