0
0
Kotlinprogramming~5 mins

Number literal formats (underscore, hex, binary) in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Number literal formats (underscore, hex, binary)
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

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
10About 10 steps to read and convert
100About 100 steps to read and convert
1000About 1000 steps to read and convert

Pattern observation: The work grows directly with the length of the number literal.

Final Time Complexity

Time Complexity: O(n)

This means the time to process number literals grows in a straight line with the number of digits or bits.

Common Mistake

[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.

Interview Connect

Understanding how number formats affect processing helps you explain how programs handle data efficiently, a useful skill in many coding situations.

Self-Check

"What if we used very large number literals repeatedly inside a loop? How would the time complexity change?"