Quantcast
Channel: How to check if a number is a power of 2 - Stack Overflow
Viewing all articles
Browse latest Browse all 38

Answer by K_holla for How to check if a number is a power of 2

$
0
0

This program in java returns "true" if number is a power of 2 and returns "false" if its not a power of 2

// To check if the given number is power of 2import java.util.Scanner;public class PowerOfTwo {    int n;    void solve() {        while(true) {//          To eleminate the odd numbers            if((n%2)!= 0){                System.out.println("false");                break;            }//  Tracing the number back till 2            n = n/2;//  2/2 gives one so condition should be 1            if(n == 1) {                System.out.println("true");                break;            }        }    }    public static void main(String[] args) {        // TODO Auto-generated method stub        Scanner in = new Scanner(System.in);        PowerOfTwo obj = new PowerOfTwo();        obj.n = in.nextInt();        obj.solve();    }}OUTPUT : 34false16true

Viewing all articles
Browse latest Browse all 38

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>