Write a program to count the occurrence of 1 and print it's position of a number which is converted to binary number.
import java.util.*;
public class DigitCount {
public static void toBinary(int decimal){
int binary[] = new int[100];
int index = 0;
while(decimal > 0){
binary[index++] = decimal%2;
decimal = decimal/2;
}
int count = 0, lo=0;
int loc[] = new int[100];
for(int i = index-1;i >= 0;i--){
if(binary[i] == 1) {
count += 1;
loc[lo++]=i;
}
}
System.out.print(count);
for(int i = lo-1;i >= 0;i--) {
System.out.print("#"+loc[i]);
}
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n= sc.nextInt();
toBinary(n);
}
}
Comments
Post a Comment