Q:

Kotlin program to convert decimal to binary

belongs to collection: Kotlin Basic Programs

0

We are given a decimal number and we will create a Kotlin program to convert decimal number to binary.

To convert decimal number to binary, we will recursively divide the decimal number by 2 and save the remainder found till the decimal number vanquishes.

Example:

    Input:
    Decimal number = 12

    Recursive division:
Number Quotient Remainder
12 6 0
6 3 0
3 1 1
1 0 1

    Output:
    Here, we will read the remainders in reverse order 
    which is the binary equivalent i.e. 
    1100 is the binary conversion for 12.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to convert decimal to binary in Kotlin

package com.includehelp.basic

import java.util.*

/* function to convert given decimal number into Binary */
fun getBinaryNumber(decimalNumber: Int): String {
    var decimalNumber = decimalNumber
    val binaryStr = StringBuilder()
    
    while (decimalNumber > 0) {
        val r = decimalNumber % 2
        decimalNumber /= 2
        binaryStr.append(r)
    }
    
    return binaryStr.reverse().toString()
}

// Main Method Entry Point of Program
fun main(arg: Array<String>) {
    val sc = Scanner(System.`in`)
    
    println("Enter Decimal Number  : ")
    //Input Decimal Number
    val decimalNumber: Int = sc.nextInt()
    
    // Call function to Convert Decimal into binary
    val binaryNumber = getBinaryNumber(decimalNumber)
    // Print Binary Number
    println("Binary Number : $binaryNumber")
}

Output

Run 1:
Enter Decimal Number  :
15
Binary Number : 1111
-----
Run 2:
Enter Decimal Number  :
12345
Binary Number : 11000000111001
----
Run 3:
Enter Decimal Number  :
545654
Binary Number : 10000101001101110110

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Kotlin Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Kotlin program to convert decimal number to octal ... >>
<< Kotlin program to check whether number is binary o...