Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- fun main() {
- var num1 = listOf(1,2,3)
- var num2 = listOf(1,2,3)
- println(sum(num1, num2)) // [0, 2, 4, 6]
- num1 = listOf(9,9,9)
- num2 = listOf(1)
- println(sum(num1, num2)) // [1, 0, 0, 0]
- num1 = listOf(9,9,9)
- num2 = listOf(9,9,9)
- println(sum(num1, num2)) // [1, 9, 9, 8]
- num1 = listOf(5,4,4)
- num2 = listOf(4,5,6)
- println(sum(num1, num2)) // [1, 9, 9, 8]
- }
- // [9,9]
- // [9,9]
- // [0, 1, 9, 8]
- fun sum(num1: List<Int>, num2: List<Int>): List<Int> {
- val resultSize = max(num1.size, num2.size) + 1
- val result = ArrayList<Int>(resultSize)
- (0 until resultSize).forEach { _ ->
- result.add(0)
- }
- var carry = 0
- var p1 = num1.size - 1
- var p2 = num2.size - 1
- var resultP = resultSize - 1
- while(p1 >= 0 || p2 >= 0 || carry != 0) {
- val firstLatestNum = if (p1 >= 0) num1[p1--] else 0
- val secondLatestNum = if (p2 >= 0) num2[p2--] else 0
- val sum = firstLatestNum + secondLatestNum + carry
- result[resultP--] = sum % 10
- carry = sum / 10
- }
- return result
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement