Your little brother has a math assignment to find whether the given u power of 2. If it is a power of 2 then he has to find the sum of the digit power of 2, then he has to find the next number which is a power of your help to validate his work. But you are already busy playing video games Develop a program so that your brother can validate his work by
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int u = in.nextInt();
int one = 0;
long sum = 0;
String bits = Integer.toBinaryString(u);
for (int i = 0; i < bits.length(); i++) {
if (bits.charAt(i) == '1') {
one++;
}
}
if (one == 1) {
System.out.println(u + " is power of 2");
do {
sum += (Math.pow(2, u % 10));
u /= 10;
} while (u != 0);
System.out.println("Sum of digits power of 2 = " + sum);
System.out.println(Integer.parseInt(bits + '0', 2));
} else {
System.out.println(u + " is not power of 2");
}
}
}
Comments
Leave a comment