Advertisement
Kostiggig

Untitled

Sep 10th, 2023
1,297
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.10 KB | None | 0 0
  1. fun main() {
  2.  
  3.     var num1 = listOf(1,2,3)
  4.     var num2 = listOf(1,2,3)
  5.  
  6.     println(sum(num1, num2)) // [0, 2, 4, 6]
  7.  
  8.     num1 = listOf(9,9,9)
  9.     num2 = listOf(1)
  10.     println(sum(num1, num2)) // [1, 0, 0, 0]
  11.  
  12.     num1 = listOf(9,9,9)
  13.     num2 = listOf(9,9,9)
  14.     println(sum(num1, num2)) // [1, 9, 9, 8]
  15.  
  16.     num1 = listOf(5,4,4)
  17.     num2 = listOf(4,5,6)
  18.     println(sum(num1, num2)) // [1, 9, 9, 8]
  19. }
  20.  
  21. // [9,9]
  22. // [9,9]
  23. // [0, 1, 9, 8]
  24. fun sum(num1: List<Int>, num2: List<Int>): List<Int> {
  25.  
  26.     val resultSize = max(num1.size, num2.size) + 1
  27.     val result = ArrayList<Int>(resultSize)
  28.     (0 until resultSize).forEach { _ ->
  29.         result.add(0)
  30.     }
  31.  
  32.     var carry = 0
  33.     var p1 = num1.size - 1
  34.     var p2 = num2.size - 1
  35.  
  36.     var resultP = resultSize - 1
  37.  
  38.     while(p1 >= 0 || p2 >= 0 || carry != 0) {
  39.         val firstLatestNum = if (p1 >= 0) num1[p1--] else 0
  40.         val secondLatestNum = if (p2 >= 0) num2[p2--] else 0
  41.         val sum = firstLatestNum + secondLatestNum + carry
  42.  
  43.         result[resultP--] = sum % 10
  44.         carry = sum / 10
  45.     }
  46.     return result
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement