题解 | #进制转换#

进制转换

http://www.nowcoder.com/practice/8f3df50d2b9043208c5eed283d1d4da6

import java.util.Scanner;

/**
 * @author Shan
 * @create 2021-05-31 下午 8:02
 */
public class test {
    public static void main(String args[]) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder builder = new StringBuilder();
        while (scanner.hasNext()) {
            char[] chars = scanner.nextLine().toCharArray();
            int i = 0;
            if (chars.length > 2 && chars[i] == '0' && (chars[1] == 'x' || chars[1] == 'X')) {
                i = i + 2;      //跳过‘0x’ || ‘0X’
            }
            int result = 0;
            while (i < chars.length) {
                int temp = 0;
                if(chars[i]=='a' || chars[i]=='A')
                    temp=10;
                else if(chars[i]=='b' || chars[i]=='B')
                    temp=11;
                else if(chars[i]=='c' || chars[i]=='C')
                    temp=12;
                else if(chars[i]=='d' || chars[i]=='D')
                    temp=13;
                else if(chars[i]=='e' || chars[i]=='E')
                    temp=14;
                else if(chars[i]=='f' || chars[i]=='F')
                    temp=15;
                else
                    temp=chars[i]-'0';
                result = result * 16 + temp;
                i++;
            }
            System.out.println(result);
        }
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务