Passion and Patience

Work Hard, Play Hard

导航

牛客 HJ5进制转换

暴力匹配求解:

java字符与整型之间的转换:char-'0'(char) int,字符串与整型转换:String.valueOf(int)Integer.parseInt(str)

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.nextLine();
        int a = 0;
        int n = s.length();
        for(int i = n-1;i>=2;i--){
            int valIdx = s.charAt(i)-'0';
            switch(s.charAt(i)){
                case 'A':
                    valIdx = 10;
                    break;
                case 'B':
                    valIdx = 11;
                    break;
                case 'C': 
                    valIdx = 12;
                    break;
                case 'D':
                    valIdx = 13;
                    break;
                case 'E':
                    valIdx = 14;
                    break;
                case 'F':
                    valIdx = 15;
                    break;
            }
            a+=valIdx*Math.pow(16,n-i-1);
        }
        String ResultTran = String.valueOf(a);
        System.out.println(ResultTran);
    }
}

恒成立调用API完成16进制转换:

import java.io.*;
import java.util.*;

public class Main{
    public static void main(String[] args) throws Exception{
        Scanner sc = new Scanner(System.in);
        while(sc.hasNextLine()){
            String s = sc.nextLine();
            System.out.println(Integer.parseInt(s.substring(2,s.length()),16));
        }
    }
}

posted on 2024-04-05 21:39  安静的聆  阅读(11)  评论(0编辑  收藏  举报