Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
- int com=in.nextInt();
- String novobin="";
- double novodec=0;
- int x=0;
- for(int c=0;c<com;c++) {
- String tipo=in.next();
- int num=in.nextInt();
- String bin=Integer.toString(num);
- int tamanho=bin.length();
- if(tipo.equals("dec")) {
- String j=NumtoBin(num, novobin);
- System.out.println(j);
- }else if(tipo.equals("bin")){
- int d=(int)BintoNum(bin,novodec,tamanho,x);
- System.out.println(d);
- }else {
- System.out.println("comando invalido.");
- }
- }
- }
- public static String NumtoBin(int num, String novobin) {
- if(num<2) {
- if(num==0) {
- return novobin;
- }else {
- return num+novobin;
- }
- }else {
- if(num%2==0) {
- novobin="0"+novobin;
- }else {
- novobin="1"+novobin;
- }
- }
- num=num/2;
- return NumtoBin(num, novobin);
- }
- public static double BintoNum (String bin, double novodec,int tamanho, int x) {
- if(tamanho==x) {
- return novodec;
- }else {
- if(bin.charAt(x)=='1') {
- novodec=novodec+Math.pow(2, tamanho-1-x);
- }else {
- }
- }
- return BintoNum(bin,novodec, tamanho, x+1);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement