I wrote this program to find out if a given input is power 2, this program does not work for a very large number, such as 10 ^ 18 or so. what should I do

This is a program to check if the input is power 2 or not. This program works fine for inputs up to 8 digits, but when I input, how 10 18 it does not work, 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");
            }
        }
    }
}
+4
source share
5 answers

, 10 18 Java int, 2 31 -1 2 * 10 9. , long int, 9 * 10 18 , BigInteger:

BigInteger n = new BigInteger(numericString);
BigInteger test = n.and(n.subtract(BigInteger.ONE));
if (test.equals(BigInteger.ZERO)) {
    ...
}
+7

String, BigInteger, ,

BigInteger inputNumber = new BigInteger(inputString);

. BigInteger ?, BigInteger.

+1

long ,

n = sc.nextInt();

n = sc.nextLong();

n int.

0

BigInteger, Serializable, Comparable<BigInteger>. BigInteger , GCD, , , .

input="Number"
BigInteger number = new BigInteger(input);
//Do your stuff

0

:

 k = sc.nextLong();
Hide result
0

Source: https://habr.com/ru/post/1622418/


All Articles