题解 | #进制转换#

进制转换

https://www.nowcoder.com/practice/8f3df50d2b9043208c5eed283d1d4da6

3、将十六进制字母转换成对应的数字

import java.util.Scanner;


public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String hex = in.nextLine();
        hex = hex.substring(2); //去掉0x

        int res = 0;
        int count = 0;
        for(int i = hex.length() - 1; i >= 0; i--){
            char c = hex.charAt(i);
            int num1 = 0;
            //获取十六进制字母所对应的数值
            if(c >= '0' && c <='9'){
                num1 = c - '0';
            }else if(c >= 'a' && c <= 'f'){
                num1 = c - 'a' + 10;
            }else if(c >= 'A' && c <= 'F'){
                num1 = c - 'A' + 10;
            }

            int num2 = (int)Math.pow(16, (double) count);
            count++;
            res += num1 * num2;
        }
        System.out.println(res);
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务