Q:

Kotlin program for Decimal to Binary conversion using recursion

belongs to collection: Kotlin Recursion Programs

0

Given a decimal number, we have to convert it into binary using recursion.

Example:

    Input:
    num = 113

    Output:
    1110001

All Answers

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

Program for Decimal to Binary conversion using recursion in Kotlin

package com.includehelp.basic

import java.util.*

/* function to convert given decimal into Binary */
fun binaryRecursion(_decimalNumber: Long): String {
    var decimalNumber = _decimalNumber
    if (decimalNumber > 0) {
        val a: Long = decimalNumber % 2
        decimalNumber /= 2
        return a.toString() + binaryRecursion(decimalNumber)
    }
    return ""
}

//Main function Entry Point of Program
fun main(arg: Array<String>) {
        //Input Stream
    val sc = Scanner(System.`in`)

    //Input Integer Number
    println("Enter Decimal Number  : ")
    var decimal: Long = sc.nextLong()

    val binary= binaryRecursion(decimal).reversed()
    println("Binary of $decimal using Recursion : $binary")
}

Output

Run 1:
Enter Decimal Number  :
45
Binary of 45 using Recursion : 101101
-----
Run 2:
Enter Decimal Number  :
113
Binary of 113 using Recursion : 1110001

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

total answers (1)

<< Kotlin program to find GCD/HCF of two numbers usin...