Program to convert a Decimal Number to Binary and count the number of 1s in Kotlin

In this article, we will learn to write Kotlin program to Convert a Decimal Number to Binary and count the number of 1s in Kotlin.

Program Code:
import java.util.Scanner

fun main(args: Array<String>) {
    var n: Int
    var count = 0
    var a: Int
    var x = ""
    val s = Scanner(System.`in`)
    print("Enter any decimal number:")
    n = s.nextInt()
    while (n > 0) {
        a = n % 2
        if (a == 1) {
            count++
        }
        x = x + "" + a
        n = n / 2
    }
    println("Binary number:$x")
    println("No. of 1s:$count")
}
Output:
Enter any decimal number:123
Binary number:1101111
No. of 1s:6
Description:
In the program source code, it takes input from a user to enter any decimal number. Next step is to convert the entered decimal number into a binary number with the help of division and modulus operations along with if conditions and for loop to achieve the desired output.

Post a Comment

0 Comments