题解 | 进制转换

进制转换

https://www.nowcoder.com/practice/ac61207721a34b74b06597fe6eb67c52

import java.util.*;
import java.lang.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static String transform(int M, int N){
        if(M==0) return "0";
        StringBuffer sb = new StringBuffer();
        int start = 0;
        if(N<=9){
            while((int)Math.pow(N,start)<M) start+=1;
            if((int)Math.pow(N,start)>M) start-=1;
            while(M>0 || start>=0){
                sb.append(M/(int)Math.pow(N,start));
                M = M%((int)Math.pow(N,start));
                start-=1;
            }
        }else{
            while((int)Math.pow(N,start)<M) start+=1;
            if((int)Math.pow(N,start)>M) start-=1;
            while(M>0 || start>=0){
                int tmp = M/(int)Math.pow(N,start);
                if(tmp<10) sb.append(tmp);
                else sb.append((char)('A'+tmp-10));
                M = M%((int)Math.pow(N,start));
                start-=1;
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int M = in.nextInt(), N = in.nextInt();
        String f = "";
        //解决负数问题
        if(M<0){
            f = "-";
            M = -M;
        }
        System.out.println(f+transform(M,N));
    }
}

1.注意负数

2.注意题目要求转换字母

3.注意前导0和后缀0

全部评论

相关推荐

09-21 21:14
门头沟学院
否极泰来来来来:和他说:这里不好骂你,我们加个微信聊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务