首页 > 试题广场 >

进制转换

[编程题]进制转换
  • 热度指数:34355 时间限制: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

//M%N就是N进制的第一位,然后M/N后再取余数就是N进制第二位,以此类推,用栈可以解决。注意负数

#include <iostream>

#include <stack>

using namespace std;


int main(int argc, const char * argv[]) {

    int M,N;

    cin>>M>>N;

    stack<char> answer;

    if(M<0)

    {

        cout<<"-";

        M=-M;

    }

    while(M!=0)

    {

        if(M%N<10)

        {

            answer.push(char(M%N+48));

            M/=N;

        }

        else

        {

            answer.push(char(M%N+55));

            M/=N;

        }

    }

    while(answer.empty()!=1)

    {

        cout<<answer.top();

        answer.pop();

    }

    return 0;

}


发表于 2018-01-30 22:14:00 回复(1)
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner in=new Scanner(System.in);
		String m=in.next();
		int n=in.nextInt();	
		BigInteger bi=new BigInteger(m,10);
		System.out.println(bi.toString(n).toUpperCase());
	}
}

发表于 2017-09-02 22:30:31 回复(2)
#include<stdio.h>
int res[1000],tot=0,x,n,i;
char a[18]="0123456789ABCDEFG";
int main(){
    scanf("%d%d",&x,&n);
    if(x<0) x=-x,printf("-");
    while(x) res[tot++]=x%n,x/=n;
    for(i=tot-1;i>=0;i--) printf("%c",a[res[i]]);
}

发表于 2017-10-21 11:04:57 回复(1)
可以用StringBuilder的insert不断在前面插入新的数字,也可以用append最后再reverse。
记得对负数先求绝对值再处理,最后输出对应符号即可。
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int num = in.nextInt();
        int radix = in.nextInt();
        char[] chars = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        boolean negative = false;
        if (num < 0) negative = true;
        StringBuilder sb = new StringBuilder();
        num = Math.abs(num);
        while (num >= radix) {
            sb.insert(0, chars[num % radix]);
            num /= radix;
        }
        sb.insert(0, chars[num]);
        System.out.println((negative ? "-" : "") + sb.toString());
    }
}

发表于 2017-04-04 09:42:06 回复(1)

python解法

本來想用递归解的,结果超出最大深度,只能用循环做了。

def baseN(num, b):
    res = ""
    if num > 0:
        while num:
            res = "0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ"[num % b] + res
            num = num // b
        return res
    else:
        num = -num
        while num:
            res = "0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ"[num % b] + res
            num = num // b
        return "-" + res


a, b = map(int, input().split())
print(baseN(a, b))
发表于 2018-04-13 10:21:05 回复(2)
// 这个只需要按照进制转换直接计算就行了,要注意负数的问题
import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        HashMap<Integer,Character> hm = new HashMap<Integer,Character>();
        hm.put(10,'A');hm.put(11,'B');
        hm.put(12,'C');hm.put(13,'D');
        hm.put(14,'E');hm.put(15,'F');
        while(sc.hasNext()){
            int m = sc.nextInt();
            int n = sc.nextInt();
            StringBuilder sb = new StringBuilder();
            boolean flag = false;
            if(m<0){
                flag = true;
                m = 0-m;
            }
            while(m>0){
                int t = m%n;
                sb.append(hm.get(t)==null?t:hm.get(t)+"");
                m = m/n;
            }
            if(flag)
                System.out.println("-" + sb.reverse().toString());
            else
            	System.out.println(sb.reverse().toString());
        }
    }
}

发表于 2017-09-05 10:09:34 回复(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.Scanner;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int M = sc.nextInt();
        int N = sc.nextInt();
        boolean isMinByZero = (M < 0);
        M = Math.abs(M);
        String str = "";
        str = M%N >= 10 ? (char)('A'+(M%N-10)) + str : (M % N) + str;
        while (M / N > 0){          
            M /= N;
            str = M%N >= 10 ? (char)('A'+(M%N-10)) + str : (M % N) + str;
        }
        if (isMinByZero) {
            System.out.println("-" + str);
        }else {
            System.out.println(str);
        }       
    }
}

发表于 2017-09-25 19:21:29 回复(0)
importjava.util.Stack;
importjava.util.Scanner;
publicclassMain{
    publicstaticvoidmain(String[] args){
        intn,base;
        Scanner scanner = newScanner(System.in);
        Stack S=newStack();
        while(scanner.hasNextInt()){
        n=scanner.nextInt();
        base=scanner.nextInt();
        chardigit[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        while(n>0){
            S.push(digit[n%base]);
            n/=base;
        }
        while(!S.empty()){
           System.out.print(S.pop());
        }
           System.out.println();
        }
    }   
}

发表于 2017-01-06 20:21:20 回复(3)
#include <iostream>
using namespace std;

char buf[50];

int main()
{
    int m, n;
    while (scanf("%d%d", &m, &n) != EOF)
    {
        int index = 0;
        int mm = m;
        if(m<0) m = -m;//注意m为负的情况,直接转换为正就行,因为负的结果实际上就是正的结果的负
        do{
            buf[index++] = (m%n < 10)?m%n+'0':m%n-10+'A';
            m/=n;
        }while(m);
        if(mm<0)//在数组的最后一位加上一个负号,一会儿直接打印出来
            buf[index++] = '-';
        for(int i = index-1; i >= 0; i--)
            printf("%c", buf[i]);

        printf("\n");
    }
    return 0;

}

发表于 2020-07-06 14:15:48 回复(0)
#include<iostream>
#include<string>
using namespace std;

int main()
{
    int m, n;
    string s, table = "0123456789ABCDEF";
    cin >> m >> n;
    if (m == 0) cout << "0" << endl;
    while (m)
    {
        if (m < 0)
        {
            m = -m;
            cout << "-";
        }
        s = table[m%n] + s;
        m /= n;
    }
    cout << s << endl;
    return 0;
}

发表于 2019-10-11 14:27:10 回复(0)
import java.util.Scanner;

public class Main{
    public static String convert(int num,int radix){
        if (num == 0){
            return "0";
        }
        char[] table = new char[]{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        StringBuilder builder = new StringBuilder();
        
        //默认是非负数
        boolean flag = false;
        if(num < 0){
            flag = true;
            num = - num;
        }
        
        while(num > 0){
            builder.append(table[num % radix]);
            num /= radix;
        }
        if(flag){
            builder.append('-');
        }
        return builder.reverse().toString();
    } 
    
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        int num = scanner.nextInt();
        int radix = scanner.nextInt();
        System.out.println(convert(num,radix));
    }
}


发表于 2019-07-20 13:34:44 回复(0)
#include<iostream> 
using namespace std;
char hashT[16]={//查表省去判断条件
    '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
};
void change(int m,int n){//递归处理
    if(m==0) return;
    change(m/n,n);    
    cout<<hashT[m%n];
}
int main(){
    int m,n;
    while(cin>>m>>n){
        if(m<0||m>0){
            if(m<0){//考虑负数的情况
                cout<<"-";
                m=-m;    
            }    
            change(m,n);
            cout<<endl;    
        }else{
            cout<<'0'<<endl;//考虑为0时的情况
        }     
    }
    return 0;
}

发表于 2019-01-01 13:42:08 回复(0)
package train;
import java.util.Scanner;
/**
 * 将十进制数M转化为N进制数 输入描述: 输入为一行,M(32位整数)、N(2 ≤ N ≤ 16),以空格隔开。
 * 输出描述: 为每个测试实例输出转换后的数,每个输出占一行。如果N大于9,则对应的数字规则参考16进制(比如,10用A表示,等等)
 * 
 * @author jun
 *
 */
public class JavaTest_87 {

    public static void getValue(int m, int n) {
        int a[] = new int[100];
        int i = 0;
        while (m != 0) {
            a[i] = m % n;
            m = m / n;
            i++;
        }
        for (int j = i; j > 0; j--) {

            if (a[j - 1] < 0) {// j-1是因为m=0时,i++算了一次。所以j=i,j需要减去多的1。

                for (int k = 0; k < i - 1; k++) {

                    a[k] = Math.abs(a[k]);

                }
            }
            if (a[j - 1] > 9 || a[j - 1] < -9) {
                System.out.print((char) (a[j - 1] + 55));//ABCEF字符转换
            } else

                System.out.print(a[j - 1] + "");

        }

    }

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        int m = in.nextInt();
        int n = in.nextInt();

        getValue(m, n);

    }
}

发表于 2018-08-14 17:03:24 回复(0)
#include <stdio.h>
intmain()
{
    intnumber, nBase, rOfNumber, iIndex=0, nFlag=0;
    charresult[100];
    scanf("%d %d", &number, &nBase);
    if(number==0)
    {
        printf("0");
        return 0;
    }
    else if(number<0)
    {
        printf("-");
        number = -number;
    }
    while(number!=0)
    {
        rOfNumber = number%nBase;
        if(rOfNumber<10)
            result[iIndex++] = '0'+rOfNumber;
        else
            result[iIndex++] = 'A'+rOfNumber-10;
        number /= nBase;
    }
    while(iIndex)
    {
        printf("%c", result[--iIndex]);
    }
    return 0;
}

发表于 2018-06-10 22:29:58 回复(0)
#include<iostream>
#include<vector>
using namespace std;
//进制转换,要考虑mode>9的情况,还要考虑负数
int main()
{
    int num,mode;
    while(cin>>num>>mode)
    {
        vector<int> ret;
        int flag = 0;
        if(num <0)
        {
            num = -num;
            flag =1;
        }
            
        while(num>0)
        {
            ret.push_back(num % mode);
            num /=mode;
        }
        vector<int>::reverse_iterator it;
        for(it = ret.rbegin();it!=ret.rend();++it)
        {
            if(flag == 1)
            {
                cout<<"-";
                flag = 0;
            }
                
            if(*it<9)
                cout<<*it;
            else
                cout<<(char)((*it-10)+'A');
        }
        cout<<endl;
    }
    return 0;
}

发表于 2018-06-08 19:09:15 回复(0)
def solution(N,num):
    ref = "0123456789ABCDEF"
    result = [ref[num%N]]
    while num//N !=0:
        num = num//N
        result.append(ref[num%N])
    result.reverse()
    return "".join(result)

num, N = map(int, input().split())

if num < 0:
    print("-"+solution(N,-num))
else:
    print(solution(N,num))

发表于 2018-04-10 00:16:41 回复(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)
//记得处理符号
#include<stdio.h>
int main() {
    int m,n;
    while (scanf("%d%d", &n, &m) != EOF) {
        int tag = 1;
        if (n < 0) { n = -n; tag = 0; }
        char A[40];
        int p = 0;
        int x;
        do {
            x= n % m;
            A[p++] = x < 10 ? x + '0' : x + 'A' - 10;
            n /= m;
        } while (n);
        if (tag == 0) printf("-");
        for (p--; p >= 0; p--) {
            printf("%c", A[p]);
        }
        printf("\n");
    }
    return 0;
}

发表于 2018-03-04 22:55:38 回复(0)