进制转换

题目描述

写出一个程序,接受一个十六进制的数值字符串,输出该数值的十进制字符串。(多组同时输入 )

输入描述:

输入一个十六进制的数值字符串。

输出描述:

输出该数值的十进制字符串。

输入例子:
0xA
输出例子:
10
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while(in.hasNext()) {
            String str = in.nextLine();
            System.out.println(convert(str.substring(2)));
        }
    }
    
    private static int convert(String str) {
        int count = 0;
        int temp = 0;
        int n = 0;
        char ch;
        /*
         * 将字符转换为数字
         */
        while(count < str.length()) {
            ch = str.charAt(str.length() - count - 1);
            if(ch >= '0' && ch <= '9')  {
                temp = ch - '0';
            } else if(ch >= 'A' && ch <= 'Z') {
                temp = ch - 'A' + 10;
            } else if(ch >= 'a' && ch <= 'z') {
                temp = ch - 'a' + 10;
            } else {
                break;
            }
            
            n += temp * Math.pow(16, count);  // 按公式计算
            count ++;
        }
        return n;
    }
}
原文地址:https://www.cnblogs.com/zywu/p/5805859.html