華為線上程式設計題系列-5-進位制轉換
阿新 • • 發佈:2019-01-01
問題描述:
1. 問題涉及知識點.
- 字串遍歷.
2. 自己解法.
- 先做一個
hasNext()
的無限迴圈. - 取一個輸入’0xA’,通過split獲取substring的方式取x之後的字串.
- 遍歷新的字串.通過16的i次方的方式累加.
package com.chaoxiong.niuke.huawei;
import java.util.Scanner;
public class HuaWei_5 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()){
String in = scanner.nextLine();
String []tmp = in.split("x");
String key = tmp[tmp.length-1];
int result = Convert(key);
System.out.println(result);
}
}
private static int Convert(String key) {
char []charArr = key.toCharArray();
int result = 0;
for(int i=0;i<charArr.length;i++){
result = (int) (result+char2Int(charArr[i])*(Math.pow(16,charArr.length-1-i)));
}
return result;
}
private static int char2Int(char c) {
switch (c){
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
case 'A':
return 10;
case 'B':
return 11;
case 'C':
return 12;
case 'D':
return 13;
case 'E':
return 14;
case 'F':
return 15;
default:
return 0;
}
}
}
3. 優質答案.
優化方法
1:不用split切分,而是通過substring(2)直接取第二個之後的字串.