This is a program to check if an input is power of 2 or not. This program is running fine for inputs up to 8 digits but when I am giving input like 1018, it is not working, What should I do?
import java.util.Scanner;
public class search {
public static void main(String [] args){
//to take how many inputs are there
Scanner sc = new Scanner(System.in);
int k ;
k = sc.nextInt();
for(int i = 0 ;i<k;i++){
// input number n
long n ;
n = sc.nextInt();
if ((n > 0) && ((n & (n - 1)) == 0)){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
}
}
The problem is that 1018 is out of range of Java int
, which stores numbers up to 231-1, or roughly 2*109. You can expand the range of your program by using long
in place of int
to accept numbers up to 9*1018, or to make it accept virtually unlimited range by using BigInteger
:
BigInteger n = new BigInteger(numericString);
BigInteger test = n.and(n.subtract(BigInteger.ONE));
if (test.equals(BigInteger.ZERO)) {
...
}
You need to get your input number as String
then use BigInteger
class to avoid limit surpassing problem,
BigInteger inputNumber = new BigInteger(inputString);
Also, refer What does BigInteger having no limit mean? to know more about BigInteger
limits.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With