Number literal formats (underscore, hex, binary) in Kotlin - Time & Space Complexity
We want to understand how the time it takes to read and use number literals changes as the numbers get bigger or more complex.
How does the format of a number affect the work the program does?
Analyze the time complexity of the following code snippet.
val decimal = 1_000_000
val hex = 0xFF_EC_DE_5E
val binary = 0b11010010_01101001_10010100_10010010
fun printNumbers() {
println(decimal)
println(hex)
println(binary)
}
This code defines numbers using decimal with underscores, hexadecimal, and binary formats, then prints them.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading and converting the number literals once when the program starts.
- How many times: Each number literal is processed only once during initialization.
As the number literals get longer (more digits or bits), the time to read and convert them grows a little.
| Input Size (digits/bits) | Approx. Operations |
|---|---|
| 10 | About 10 steps to read and convert |
| 100 | About 100 steps to read and convert |
| 1000 | About 1000 steps to read and convert |
Pattern observation: The work grows directly with the length of the number literal.
Time Complexity: O(n)
This means the time to process number literals grows in a straight line with the number of digits or bits.
[X] Wrong: "Using underscores or hex/binary formats makes the program slower in a big way."
[OK] Correct: The program only reads and converts these numbers once, so the difference is very small and grows only with the length of the number.
Understanding how number formats affect processing helps you explain how programs handle data efficiently, a useful skill in many coding situations.
"What if we used very large number literals repeatedly inside a loop? How would the time complexity change?"