0
0
Kotlinprogramming~5 mins

String to number conversion in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: String to number conversion
O(n)
Understanding Time Complexity

When converting a string to a number, the time it takes depends on the length of the string.

We want to know how the work grows as the string gets longer.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


fun stringToInt(s: String): Int {
    var result = 0
    for (char in s) {
        val digit = char - '0'
        result = result * 10 + digit
    }
    return result
}
    

This code converts a string of digits into an integer by processing each character one by one.

Identify Repeating Operations
  • Primary operation: Looping through each character in the string.
  • How many times: Exactly once for each character in the input string.
How Execution Grows With Input

As the string gets longer, the number of steps grows in a straight line with the length.

Input Size (n)Approx. Operations
10About 10 steps
100About 100 steps
1000About 1000 steps

Pattern observation: Doubling the string length roughly doubles the work done.

Final Time Complexity

Time Complexity: O(n)

This means the time to convert grows directly with the length of the string.

Common Mistake

[X] Wrong: "Converting a string to a number takes the same time no matter how long the string is."

[OK] Correct: Each character must be read and processed, so longer strings take more time.

Interview Connect

Understanding how string length affects conversion time helps you explain efficiency clearly and shows you know how input size matters in real code.

Self-Check

"What if we changed the code to convert a string to a floating-point number with decimals? How would the time complexity change?"