题解 | #进制转换#

进制转换

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String a = in.nextLine();
            System.out.println(hex2Ten(a));
        }
    }

    public static Integer hex2Ten(String hex){
        String input=hex.substring(2);
        int index=0;
        int tenOut=0;
        //   543210
        // oxABC456
        //
        int j=input.length()-1;
        while (index<input.length()&&j>=0){
            char c = input.charAt(index);
            char c1 = Character.toLowerCase(c);
            int k=0;
            if(c1>'9'){
                k=c1-Character.toLowerCase('A')+10;
            }else{
                k=c1-'0';
            }
            tenOut+=k*Math.pow(16,j);
            j--;
            index++;
        }
        return tenOut;
    }
}

全部评论

相关推荐

09-24 18:30
已编辑
长春工业大学 产品经理
小肥罗:HR就是好人的缩写哈哈哈哈
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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