码迷,mamicode.com
首页 > 编程语言 > 详细

经典算法题-十六进制转化十进制

时间:2020-03-24 23:33:52      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:math   can   接受   art   parse   十六进制   输出   next   import   

使用Java写出一个程序:接受一个十六进制的数,输出该数值的十进制表示。(多组同时输入 )

 

import java.util.Scanner;

public class number {
    private static final String A = "A";
    private static final String B = "B";
    private static final String C = "C";
    private static final String D = "D";
    private static final String E = "E";
    private static final String F = "F";

    public static int change(String string) {
        int[] data = new int[string.length() - 2];
        int result = 0;
        for (int i = 0; i < string.length() - 2; i++) {
            String sub = string.substring(i + 2, i + 3);
            switch (sub) {
                case A:
                    data[i] = 10;
                    break;
                case B:
                    data[i] = 11;
                    break;
                case C:
                    data[i] = 12;
                    break;
                case D:
                    data[i] = 13;
                    break;
                case E:
                    data[i] = 14;
                    break;
                case F:
                    data[i] = 15;
                    break;
                default:
                    data[i] = Integer.parseInt(sub);
            }
            result += data[i] * Math.pow(16, string.length() - 2 - i - 1);

        }
       return result;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String string = scanner.nextLine();
            int result = change(string);
            System.out.println(result);
        }
    }
}

 

 

 

经典算法题-十六进制转化十进制

标签:math   can   接受   art   parse   十六进制   输出   next   import   

原文地址:https://www.cnblogs.com/fcbyoung/p/12562703.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!