Advertisement
Guest User

Untitled

a guest
Mar 18th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.17 KB | None | 0 0
  1. public static void main(String[] args) {
  2.         Scanner in = new Scanner(System.in);
  3.         int com=in.nextInt();
  4.         String novobin="";
  5.         double novodec=0;
  6.         int x=0;
  7.         for(int c=0;c<com;c++) {
  8.             String tipo=in.next();
  9.             int num=in.nextInt();
  10.             String bin=Integer.toString(num);
  11.             int tamanho=bin.length();
  12.             if(tipo.equals("dec")) {
  13.                 String j=NumtoBin(num, novobin);
  14.                 System.out.println(j);
  15.             }else if(tipo.equals("bin")){
  16.                 int d=(int)BintoNum(bin,novodec,tamanho,x);
  17.                 System.out.println(d);
  18.             }else {
  19.                 System.out.println("comando invalido.");
  20.             }
  21.         }
  22.  
  23.     }
  24.  
  25.     public static String NumtoBin(int num, String novobin) {
  26.         if(num<2) {
  27.             if(num==0) {
  28.                 return novobin;
  29.             }else {
  30.                 return num+novobin;
  31.             }
  32.         }else {
  33.             if(num%2==0) {
  34.                 novobin="0"+novobin;
  35.             }else {
  36.                 novobin="1"+novobin;
  37.             }
  38.         }
  39.         num=num/2;
  40.         return NumtoBin(num, novobin);
  41.     }
  42.     public static double BintoNum (String bin, double novodec,int tamanho, int x) {
  43.         if(tamanho==x) {
  44.             return novodec;
  45.         }else {
  46.             if(bin.charAt(x)=='1') {
  47.                 novodec=novodec+Math.pow(2, tamanho-1-x);
  48.             }else {
  49.             }
  50.         }
  51.         return BintoNum(bin,novodec, tamanho, x+1);
  52.  
  53.     }
  54.  
  55.  
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement