题解 | #进制转换#

进制转换

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

全部评论

相关推荐

Southyeung:我说一下我的看法(有冒犯实属抱歉):(1)简历不太美观,给我一种看都不想看的感觉,感觉字体还是排版问题;(2)numpy就一个基础包,机器学习算法是什么鬼?我感觉你把svm那些写上去都要好一点。(2)课程不要写,没人看,换成获奖经历;(3)项目太少了,至少2-3个,是在不行把网上学习的也写上去。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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