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:

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: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")

}

Enter any decimal number:123

Binary number:1101111

No. of 1s:6

Description:Binary number:1101111

No. of 1s:6

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.

## 0 Comments