Kotlin Program to Convert Decimal to Binary
Integer.toBinaryString(decimalNumber) or by repeatedly dividing the number by 2 and collecting remainders.Examples
How to Think About It
Algorithm
Code
fun main() {
val decimalNumber = 10
val binaryString = Integer.toBinaryString(decimalNumber)
println("Binary of $decimalNumber is $binaryString")
}Dry Run
Let's trace the decimal number 10 through the code using the manual division method.
Initial number
decimalNumber = 10
Divide by 2 and get remainder
10 / 2 = 5 remainder 0
Divide quotient by 2 and get remainder
5 / 2 = 2 remainder 1
Repeat division
2 / 2 = 1 remainder 0
Repeat division
1 / 2 = 0 remainder 1
Collect remainders in reverse
Remainders collected: 0,1,0,1 reversed to 1010
| Quotient | Remainder |
|---|---|
| 10 | 0 |
| 5 | 1 |
| 2 | 0 |
| 1 | 1 |
Why This Works
Step 1: Using built-in function
The Integer.toBinaryString() function converts the decimal number directly to its binary string representation.
Step 2: Manual conversion logic
Dividing the number by 2 and collecting remainders simulates how binary numbers are formed, with each remainder representing a binary digit.
Step 3: Reversing remainders
The binary digits are collected from least significant to most significant bit, so reversing the remainders gives the correct binary number.
Alternative Approaches
fun decimalToBinary(num: Int): String {
if (num == 0) return "0"
var number = num
val binary = StringBuilder()
while (number > 0) {
binary.append(number % 2)
number /= 2
}
return binary.reverse().toString()
}
fun main() {
val decimalNumber = 10
println("Binary of $decimalNumber is ${decimalToBinary(decimalNumber)}")
}fun Int.toBinary(): String = Integer.toBinaryString(this) fun main() { val decimalNumber = 10 println("Binary of $decimalNumber is ${decimalNumber.toBinary()}") }
Complexity: O(log n) time, O(log n) space
Time Complexity
The algorithm divides the number by 2 repeatedly until it reaches 0, which takes about log base 2 of n steps.
Space Complexity
The space needed is proportional to the number of binary digits, which is also about log base 2 of n.
Which Approach is Fastest?
Using the built-in Integer.toBinaryString() is fastest and simplest, while manual methods are educational but slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Built-in function | O(log n) | O(log n) | Quick and simple conversion |
| Manual division | O(log n) | O(log n) | Learning and understanding binary conversion |
| Extension function | O(log n) | O(log n) | Cleaner syntax using built-in method |
Integer.toBinaryString() for quick and reliable decimal to binary conversion.