Kotlin program for Decimal to Binary conversion using recursion

Kotlin | Decimal to Binary Conversion: Here, we are going to learn how to convert a given decimal number to its equivalent to binary using recursion in Kotlin programming language? Submitted by IncludeHelp, on April 27, 2020

Kotlin - Decimal to Binary conversion using recursion

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

Example:

Input:
num = 113

Output:
1110001

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

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.