Print n length binary number

2016-12-04  本文已影响0人  wxqyppqm

import java.util.Scanner;

class printBinary 
{
  void printB (int n)
  {
    for (int i=0; i< Math.pow(2,n); i++)  // 1<<n
    {
        StringBuffer sb = new StringBuffer();
        int temp = i;
        
        for(int j=0; j<n; j++){
        sb.insert (0, temp%2);
        //sb = ((temp%2) == 1) ? sb.insert(0,"1") : sb.insert(0,"0");
        temp = temp/2;
        }
        System.out.println(sb);
    }
  }
}

public class Runner
{
   public static void main(String[] args)
   {
      Scanner scan = new Scanner (System.in);
      System.out.println("Enter n:");
      int n = scan.nextInt();
      
      printBinary pB = new printBinary();
      pB.printB(n);
   }
}   

上一篇下一篇

猜你喜欢

热点阅读