String to number conversion in Kotlin - Time & Space 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.
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.
- Primary operation: Looping through each character in the string.
- How many times: Exactly once for each character in the input string.
As the string gets longer, the number of steps grows in a straight line with the length.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: Doubling the string length roughly doubles the work done.
Time Complexity: O(n)
This means the time to convert grows directly with the length of the string.
[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.
Understanding how string length affects conversion time helps you explain efficiency clearly and shows you know how input size matters in real code.
"What if we changed the code to convert a string to a floating-point number with decimals? How would the time complexity change?"