首页 > 试题广场 >

进制转换

[编程题]进制转换
  • 热度指数:34756 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
给定一个十进制数M,以及需要转换的进制数N。将十进制数M转化为N进制数

输入描述:
输入为一行,M(32位整数)、N(2 ≤ N ≤ 16),以空格隔开。


输出描述:
为每个测试实例输出转换后的数,每个输出占一行。如果N大于9,则对应的数字规则参考16进制(比如,10用A表示,等等)
示例1

输入

7 2

输出

111
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int m = scan.nextInt();
        int n = scan.nextInt();
        StringBuilder s = new StringBuilder();
        String table = "0123456789ABCDEF";
        boolean flg = false;
        if (m < 0) {
            m = -m;
            flg = true;
        } else if (m == 0) {
            s.append('0');
        }
        while (m != 0) {
            s.append(table.charAt(m % n));
            m /= n;
        }
        if (flg == true) {
            s.append("-");
        }
        s.reverse();
        System.out.println(s);

    }
}
发表于 2023-07-08 11:25:04 回复(0)
import java.util.Scanner;
import java.math.BigInteger;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (scan.hasNextInt()) { // 注意 while 处理多个 case
           
            long M=scan.nextInt();
            long s=M;
            if(s<0){
                M=-M;
            }
            int N=scan.nextInt();
            String str=String.valueOf(M);
            BigInteger bigInteger=new BigInteger(str,10);
            if(s<0){
                System.out.println("-"+bigInteger.toString(N).toUpperCase());
            }else{
                System.out.println(bigInteger.toString(N).toUpperCase());
            }
        }
    }
}
发表于 2023-03-23 08:46:25 回复(0)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();//要转换的数字
        int base = sc.nextInt();//要转换的进制

        int tmp = num;
        StringBuilder str = new StringBuilder();//把转换好的进制放到这里
        String table = "0123456789ABCDEF";

        boolean flg = false;//定义一个布尔变量标记num是正还是负
        if(num < 0) {
            //负数:要先变成正数才好操作
            num = -num;
            flg = true;//是负数
        }
        while(num != 0) {
            str.append(table.charAt(num % base));
            num /= base;
        }
        if(flg == true) {
            str.append("-");//是负数的话,把之前删下去的负号给他加回来
        }

        if(tmp == 0) {
            System.out.println("0");
        } else {
            System.out.println(str.reverse());
        }
    }
}

发表于 2022-09-09 12:12:19 回复(0)
import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        int n = sc.nextInt();
        StringBuilder sb = new StringBuilder();
        String cur = "0123456789ABCDEF";
        boolean flg = false;
        if(m == 0){
            System.out.println(m);
        }
       
        if(m < 0){
            m = -m;
            flg = true;
        }
        while(m != 0){
          sb.append(cur.charAt(m%n)); 
            m /= n;
        }
        if(flg){
            sb.append("-");
        }
        sb.reverse();
        System.out.println(sb);
    }
}

发表于 2022-03-25 19:33:22 回复(0)
import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        int M = scan.nextInt();
        int N = scan.nextInt();
        boolean flags = true;
        if(M == 0){
            System.out.print(M);
        }
        if(M < 0){
            M = -M;
            flags = false;
        }
        String str = "0123456789ABCDEF";
        Stack<Integer> stack = new Stack<>();
        while(M%N != 0||M/N !=0){
            stack.push(M%N);
            M = M/N;
        }
        int len = stack.size()-1;
        if(!flags){
            System.out.print("-");
        }
        for(int i = len ; i>=0 ; i--){
            System.out.print(str.charAt(stack.pop()));
        }
    }
}

发表于 2021-05-28 15:09:49 回复(0)
import java.util.*;
public class Main{
    public static void main(String [] args){
        Scanner sc=new Scanner(System.in);
        int a=sc.nextInt();
        int b=sc.nextInt();
        System.out.print(Integer.toString(a,b).toUpperCase());
    }
}


发表于 2019-03-14 22:51:49 回复(0)


import java.util.Scanner;

/**
 * 十进制转  2-16进制的转换
 * @author Administrator
 *
 */
public class Main {
    /**
     * 辅助数组
     */
    private static char[] ConversionArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

    /**
     * 转换后的进制数
     */
    private String BinaryNumber = "";
    
    private boolean isNegative = false;
    
    /**
     * 进制转换
     * @param Binary            进制
     * @param M                    要转换的数
     * @param BinaryNumber        转化后的数
     * @return
     */
    public String ConversionMethod(int Binary,int M){
        if(M == 0) return descNumber(BinaryNumber);
        if(M < 0) isNegative = true;
        BinaryNumber += ConversionArray[Math.abs(M % Binary)];
        ConversionMethod(Binary, M / Binary);
        return descNumber(BinaryNumber);
    }
    /**
     * 将数组倒置返回
     * @param Number
     * @return
     */
    public String descNumber(String Number){
        StringBuffer BinaryNumber = new StringBuffer("-");
        String tmp = new StringBuffer(Number).reverse().toString();
        if(isNegative){
            BinaryNumber = BinaryNumber.append(tmp);
            return BinaryNumber.toString();
        }else{
            return tmp;
        }
    }
    
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        //转换数
        int ConversionNumber = input.nextInt();
        //进制
        int Binary = input.nextInt();
        Main conversion = new Main();
        System.out.println(conversion.ConversionMethod(Binary,ConversionNumber));
    }

}

发表于 2019-01-20 15:37:11 回复(0)
import java.util.*;
public class Main{
   static StringBuffer sb = new StringBuffer();
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();    //7      8
        int n = sc.nextInt();    //2 111  3  22
        //111     
        //7,2,3
        if(m<0){
            a(Math.abs(m),n);
            sb.append('-');
        }else{
            a(m,n);
        }
        String num = sb.reverse().toString();
        System.out.println(num);
        
    }    
    public static void a(int m,int n){
        if(m%n >= 0){
           if(m%n == 10){
               sb.append('A');
           }else if(m%n == 11){
               sb.append('B');
           }else if(m%n == 12){
               sb.append('C');
           }else if(m%n == 13){
               sb.append('D');
           }else if(m%n == 14){
               sb.append('E');
           }else if(m%n == 15){
               sb.append('F');
           }else{
               sb.append(m%n) ;
           }
           if(m/n != 0){
               a((m/n),n);
           }           
        }else{
           return ;
        } 
    }
    
}

发表于 2018-11-24 23:58:22 回复(0)
import java.util.Scanner;
public class Main{
    public static void main(String[] args){
       Scanner scan = new Scanner(System.in);
       long m=scan.nextLong();
       long flag=m>=0?1:-1;
       m=m>=0?m:-m;
       int n=scan.nextInt();
       String res="";
       char[] table={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        while(m%n>0){
        res=table[(int)m%n]+res;
        m=m/n;
        }
        if(flag>0)
        {System.out.print(res);}
        else {System.out.print("-"+res);}

    }
}
//80%通过 1000000 为啥通不过啊
发表于 2018-10-26 14:37:11 回复(0)
public class Main {

    public static void main(String[] args) {
        Scanner scan=new Scanner(System.in);
        int M=scan.nextInt();
        int N=scan.nextInt();
        String str="";
        if (M<0) {
            M=-M;
            str="-";
        }
        String decode = Integer.toUnsignedString(M, N);
        System.out.println(str+decode);
        String up = decode.toUpperCase();
        System.out.println(str+up);
    }
}
发表于 2018-10-01 12:38:13 回复(0)

import java.util.*;
 
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int n = sc.nextInt();
            int m = sc.nextInt();
            String[] count ={"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
            Stack<String> stack = new Stack<String>();
            if(n==0){
                System.out.println("0");
                return;
            }
            boolean mark = false;
            if(n<0){
                n=Math.abs(n);
                mark = true;
            }
            while(n!=0){
                stack.push(count[n%m]);
                n/=m;
            }
            StringBuffer str = new StringBuffer();
            if(mark) str.append("-");
            while(stack.size()>0){
                str.append(stack.pop());
            }
            
            System.out.println(str);
        }
    }
}
发表于 2018-08-02 09:38:48 回复(0)

import java.util.Scanner;
public class Main37 {

public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    int num=sc.nextInt();
    int basic=sc.nextInt();
    StringBuffer sb=new StringBuffer();
    String diff;
    if(num<0) {
        num=Math.abs(num);
        while(num!=0) {
            diff=Integer.toString(num%basic);
            if(Integer.parseInt(String.valueOf(diff))>=10) {
                diff=String.valueOf((char)(65+(Integer.parseInt(String.valueOf(diff))-10)));
            }
            num=num/basic;
            sb.append(diff);
        }
        sb.append("-");
        System.out.println(sb.reverse().toString());
    }else {
        while(num!=0) {
            diff=Integer.toString(num%basic);
            if(Integer.parseInt(String.valueOf(diff))>=10) {
                diff=String.valueOf((char)(65+(Integer.parseInt(String.valueOf(diff))-10)));
            }
            num=num/basic;
            sb.append(diff);
        }
        System.out.println(sb.reverse().toString());
    }

}

}
辗转相除法+ASCII码转换

发表于 2018-06-23 11:15:14 回复(0)
import java.util.Arrays;
import java.util.Scanner;

public class Main {     public static void main(String[] args) {                 Scanner in  = new Scanner(System.in);         int m = in.nextInt();         int n = in.nextInt();         System.out.println(zhuanHuan(m, n));              }
    public static String zhuanHuan(int m,int n) {                  String tables = "0123456789ABCDEFG";         String result = "";                  if(n==0 || n==1) {                         return Integer.valueOf(m).toString();         }                  if(m == 0) {             return "0";         }         int x = m >0 ? m : -m;                  while(x!=0) {             int index = x % n;             x = x / n;             result = tables.charAt(index) + result;         }                  if(m > 0) {             return result;         }else {             return "-"+result;         }              }
}

发表于 2018-06-16 01:17:03 回复(0)
public static void Nhexadecimal(int M, int N){
        if(N < 2 || N > 16){
            System.out.println("进制不能转换。。。");
            return;
        }
        
        List<Integer> list = new ArrayList<Integer>();
        String[] showStrArr = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
        
        int remainer = 0;
        while(true){
            if(M < 0){
                M = -M;
            }
            remainer = M % N;
            list.add(remainer);
            M = M / N;
            if(M  == 0){
                break;
            }
            
        }
        
        Collections.reverse(list);
        for (int i = 0; i < list.size(); i++) {
            System.out.print(showStrArr[list.get(i)]);
        }
    }
发表于 2018-05-04 01:13:44 回复(0)
import java.util.*;
import java.util.ArrayList;
public class Main {

    public static void main(String[] args) {
//        //N进制转换器
        Scanner scanner = new Scanner(System.in);
        int M = scanner.nextInt();
        int N = scanner.nextInt();
        //查询表,
        String table = "0123456789ABCDEF";
        int flag = 1;
        if (M < 0) {
            M = -M;
            flag = 0;
        }

        Stack S = new Stack();
        decimalBaseToNBaseConvertor(M, N, S, table);
        //output
        if (flag == 0) {
            S.push('-');
        }
        while (!S.empty()) {
            System.out.print(S.pop());
        }
    }
//十进制转二进制,占用空间较多;递归算法;
/*改进:
    1. 使用堆栈来存储余数,并且利用堆栈的特点,倒序输出余数的值,N进制.堆栈是wrapper Character Object
    2. 输入用Scanner类型到存储System.in的值.(Java语言不熟悉)
    3. Object 有String 和Character.A Java String is an object of the class java.lang.
    对象有方法.比C++的String更加方面(单纯char的数组).
    This Character class also offers a number of useful class (i.e., static) methods
    for manipulating characters.
* 时间复杂度:
* 空间复杂度:*/

    public static void decimalBaseToNBaseConvertor(int M, int N, Stack<Character> S, String table) {
        if (M == 0) {
            return;
        }


        //入栈
        S.push(table.charAt(M % N));
        //下一次
        decimalBaseToNBaseConvertor(M / N, N, S, table);


    }
}

编辑于 2018-04-03 13:27:38 回复(0)
import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String rul = "0123456789ABCDEF";
        int val = sc.nextInt();
        int raw = val;
        int conv = sc.nextInt();
        boolean neg = false;
        StringBuilder sb = new StringBuilder();
        while(val!=0){
            sb.append(rul.charAt(Math.abs(val%conv)));
            val/=conv;
        }
         if(raw<0)
         sb.append("-");
        System.out.println(sb.reverse().toString());
    }
}
发表于 2018-03-30 14:46:55 回复(0)
我是真的好菜啊,大佬的脑子里都是装的啥啊!
import java.util.Scanner;
import java.util.Stack;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        int tar = sc.nextInt();
        convert(num,tar);
    }

    public static void convert(int num, int tar){
        boolean simple = true;
        if (num < 0) {
            num = -num;
            simple = false;
        }
        String[] strs = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
        Stack stack = new Stack();
        while((num)!=0){
            stack.push(strs[(num%tar)]);
            num = num/tar;
        }
        if (!simple){
            System.out.print("-");
        }
        while (stack.size() != 0){
            System.out.print(stack.pop());
        }


    }
}

发表于 2018-03-21 16:53:13 回复(0)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int num = scanner.nextInt();
        int x = scanner.nextInt();
        String string = "";
        boolean flag = false;
        if (num < 0) {
            flag = true;
            num = -1 * num;
        }
        while (num / x != 0 || num % x != 0) {
            int tmp = num % x;
            if (tmp < 10) {
                string = num % x + string;
            }else {
                char ch = (char) ('A' + (tmp - 10));
                string = ch + string;
            }
            num /= x;
        }
        if (flag)
            string = "-" + string;

        System.out.println(string);
    }
}
发表于 2018-03-18 17:30:22 回复(0)
 import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        while(sc.hasNext()) {
            int n=sc.nextInt();
            int m=sc.nextInt();
            System.out.println(Integer.toString(n, m).toUpperCase());
        }
    }
}

发表于 2018-03-03 11:09:25 回复(1)