0

I want Addition where result return type is string, but Result does not match when Addition uses Kotlin programming language

Problems example: Suppose I have 2 large strings of numbers like:

"3334567891011121314151648"
"12345678911"

Example outputs:

3334567891011133659830559

Write a program to add the two numbers together and the result return type is a string using Kotlin.

This is my coding:

fun sum(n1: String, n2: String) : String {
    return "%.0f".format(n1.toDouble() + n2.toDouble()).toString()
}

fun main() {
    println(sum("3334567891011121314151648", "12345678911"))
}

But a result like this doesn't match the example output:

3334567891011134000000000

What is the solution with my coding so that the results match the example output above.

Ken White
  • 123,280
  • 14
  • 225
  • 444
  • 1
    This is because how double data are handled inside computer (memory). Refer the answer linked https://stackoverflow.com/a/7645264/6319901. – Dark Sorrow Dec 06 '22 at 03:53

1 Answers1

0

Is this homework? It looks like a puzzle you're meant to solve, since the limits of the language (and the size of the numbers it can represent with its basic types) mean you can't just throw them together and call it a day.

Assuming that's the case, look at what they want - a String result. Just text, it doesn't have to be represented by a numerical type. So, if you had a pen and paper, how would you add those two numbers together? What steps would you take? What information are you storing as you go? What result are you building towards?

cactustictacs
  • 17,935
  • 2
  • 14
  • 25