Skip to content

Instantly share code, notes, and snippets.

@Turskyi
Last active April 14, 2022 00:29
Show Gist options
  • Save Turskyi/ec92a1543848e65466bc10745aa3e67b to your computer and use it in GitHub Desktop.
Save Turskyi/ec92a1543848e65466bc10745aa3e67b to your computer and use it in GitHub Desktop.
Given two non-negative numbers, num1 and num2 represented as strings, sum the integers together and return the result as a string.
/*
Given two non-negative numbers, num1 and num2 represented as strings, sum the integers together and return the result as a string.
Ex: Given the following values for num1 and num2...
num1 = “2”, num2 = “5”, return “7”.
Ex: Given the following values for num1 and num2...
num1 = “7”, num2 = “95”, return “102”.
* */
fun addStrings(num1: String, num2: String): String {
var i: Int = num1.lastIndex
var j: Int = num2.lastIndex
var carry: Int = 0
val sb: StringBuilder = StringBuilder()
while (i >= 0 || j >= 0 || carry != 0) {
var sum: Int = carry
// if we have a character
if (i >= 0) {
// retrieve digit by ASCII code at the current index
val digit: Int = num1[i--] - '0'
sum += digit
}
if (j >= 0) {
val digit: Int = num2[j--] - '0'
sum += digit
}
// getting the last digit if number > 10
sb.insert(0, sum % 10)
// remainder (if number bigger than 10, it will give 1)
carry = sum / 10
}
return sb.toString()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment