题解 | #进制转换2#

进制转换2

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

import java.util.*;
import java.math.BigInteger;



// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {

    public static final int BASE_A = 65;
    public static final int BASE_a = 97;

    public static BigInteger parse_to_decimal(String num, String base) {
        int n = num.length();
        BigInteger ret = new BigInteger("0");
        BigInteger basic = new BigInteger(base);
        for (int i = 0; i < n; i++) {
            char cur = num.charAt(i);
            BigInteger factor;
            if (Character.isDigit(cur)) {
                factor = new BigInteger(cur + "");
            } else {
                factor = new BigInteger(10 + (cur - BASE_A) + "");
            }
            ret = ret.add(factor.multiply(basic.pow(n - i - 1)));
        }
        return ret;
    }

    public static String parse_to_NDecimal(BigInteger num, String d) {
        if (num.equals(new BigInteger("0"))) return "0";
        StringBuilder sb = new StringBuilder();
        BigInteger base = new BigInteger(d);
        while (!num.equals(new BigInteger("0"))) {
            int bit = num.mod(base).intValue();
            sb.append(bit > 9 ? (char)(bit - 10 + BASE_a) : bit);
            num = num.divide(base);
        }
        return sb.reverse().toString();
    }


    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String M = in.next();
        String N = in.next();
        in.nextLine();
        String X = in.next();
        System.out.println(parse_to_NDecimal(parse_to_decimal(X, M), N));
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-02 18:35
简历上把1个月实习写成了3个月,会进行背调吗?
码农索隆:一个月有一个月的实习经历,三个月有三个月的实习经历
点赞 评论 收藏
分享
06-08 22:25
门头沟学院 Java
从零开始的转码生活:这hr不会打开手机不分青红皂白给所有人群发这句话,过一会再给所有人再发一遍,这肯定会有重复的,不管,再过一会再发一遍
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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