Java求一个数的二进制表示

package One;

import java.util.Scanner;

public class Binary { 
  
    public static void main(String[] args) {
   
        // read in the command-line argument
       
      Scanner sc = new Scanner(System.in);
      System.out.print("input N: ");
      long n = sc.nextLong();

        // v=2的幂的小于n的最大值,set v to the largest power of two that is <= n

        int v = 1;
        while (v <= n/2) {
            v = v * 2;
        }
  
        // check for presence of powers of 2 in n, from largest to smallest
        
              while (v > 0) {
           
           // v is not present in n 
          
            if (n < v) {
                System.out.print(0);
            }
            
             // v is present in n, so remove v from n
            
             else {
                System.out.print(1);
                n = n - v;
            }
            
          // next smallest power of 2

            v = v / 2;
        }
        System.out.println();
    }
}

你可能感兴趣的:(Java求一个数的二进制表示)