题解 | #进制转换#
进制转换
https://www.nowcoder.com/practice/8f3df50d2b9043208c5eed283d1d4da6
1. 朴素法
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNext()) { // 注意 while 处理多个 case String s = in.next().toUpperCase().substring(2); int res = 0; for(int i = 0; i < s.length(); i ++){ char ch = s.charAt(i); int num; if(ch >= 'A') num = ch - 55; else num = ch - '0'; res = res * 16 + num; } System.out.println(res); } } }
2. API
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)); } } }
import java.util.*; public class Main { public static void main(String[] args) { String s = "0xAa"; //或者 String s = "0xAA"; System.out.println(Integer.parseInt(s.substring(2), 16)); } }#华为笔试#