题解 | #进制转换#

进制转换

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

题目

写出一个程序,接受一个十六进制的数,输出该数值的十进制表示。

这里我采用了一个比较笨的方法,十六进制的字符可以拆成0-9和ABCDEF,对于0-9我采用了正则表达式,对于ABCDEF采用了if判断,并对应的赋数值,这也是字符的范围有限,不然这样写还真不行。

import java.util.*;
import java.io.*;
import java.util.regex.Pattern;
public class Main {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        String s = input.nextLine();
        int res = 0;
        int count = 0;
        for(int i = s.length()-1;i >= 2;i--){
            Pattern pattern = Pattern.compile("^[0-9]*$");
            char c = s.charAt(i);
            if(c == 'A'){
                res = res + 10*(int) Math.pow(16,count);
                count++;
            }else if(c == 'B'){
                res = res + 11*(int) Math.pow(16,count);
                count++;
            }else if(c == 'C'){
                res = res + 12*(int) Math.pow(16,count);
                count++;
            }else if(c == 'D'){
                res = res + 13*(int) Math.pow(16,count);
                count++;
            }else if(c == 'E'){
                res = res + 14*(int) Math.pow(16,count);
                count++;
            }else if(c == 'F'){
                res = res + 15*(int) Math.pow(16,count);
                count++;
            }else if(pattern.matcher(String.valueOf(c)).matches()){
                int a = Integer.parseInt(String.valueOf(c));
                res = res + a*(int) Math.pow(16,count);
                count++;
            }
        }
        System.out.println(res);
    }
}

alt

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务