题解 | #进制转换#

进制转换

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

import java.util.*;

public class Main{
     public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        while(in.hasNextLine()){
            String input = in.nextLine();
            String regex = "0X|0x";
            String temp = input.replaceAll("0x|0X", "");
//             System.out.println(temp);
//             String temp2 = input.replace("0x", "").replace("0X","");  //这个就不能用 | 拼接
//             System.out.println(temp2);
            String sNum = temp.toLowerCase();
            int result = octalToHex(sNum);
            System.out.println(result);
        }
    }
    public static int octalToHex(String src){
        int result = 0;
        int len = src.length() ;
        for (int i = 0; i < len; i++) {
            int tempNum = 0;
            int c = src.charAt(i);
            if(('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z')){
                tempNum = c - 'a' + 10;
            }else {
                tempNum = c - '0';
            }

            result += tempNum * Math.pow(16, len - i - 1);
        }
        return result;
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务