算法-蓝桥杯-算法提高 P0102 (JAVA)

1 引言

    蓝桥杯整理的工作,到此就要暂告一段落。

2 题目

    用户输入三个字符,每个字符取值范围是0-9,A-F。然后程序会把这三个字符转化为相应的十六进制整数,并分别以十六进制,十进制,八进制输出,十六进制表示成3位,八进制表示成4位,若不够前面补0。(不考虑输入不合法的情况)
输入
  1D5
输出
(注意冒号后面有一个空格)
  Hex: 0x1D5
  Decimal: 469

  Octal: 0725

3 源代码

import java.util.Scanner;  
  
public class Main {  
    public static void main(String[] args) {  
        Scanner s = new Scanner(System.in);  
        String x = s.next();//输入字符串  
        String t = Integer.valueOf(x, 16).toString();//将其转化为16进制  
        /**将字符串类型t转化为整型ten*/  
        char[] tt = new char[4];  
        int[] ttt = new int[4];  
        int ten = 0;  
        for (int i = 0; i < t.length(); i++) {  
            tt[i] = t.charAt(i);//先将字符串转化为字符  
            ttt[i] = tt[i] - '0';//将字符转化为整型  
            ten = ten * 10 + ttt[i];  
        }  
        /**判断字符位数,若不够前面补0。*/  
        if (x.length() == 1)  
            System.out.println("Hex: 0x00" + x);  
        else if (x.length() == 2)  
            System.out.println("Hex: 0x0" + x);  
        else if (x.length() == 3)  
            System.out.println("Hex: 0x" + x);  
          
        System.out.println("Decimal: "+t);//输出十进制数  
        String e = Integer.toOctalString(ten);//将十进制转化为8进制  
        /**判断字符位数,若不够前面补0。*/  
        if (e.length() == 1)  
            System.out.println("Octal: 000" + e);  
        else if (e.length() == 2)  
            System.out.println("Octal: 00" + e);  
        else if (e.length() == 3)  
            System.out.println("Octal: 0" + e);  
        if (e.length() == 4)  
            System.out.println("Octal: " + e);  
    }  
} 

4 结束语

    分享和帮助是人生一大乐事,希望可以帮助您。本人才疏学浅,如果有不当之处,还请批评指正。同时欢迎大家评论、点赞及转发!

猜你喜欢

转载自blog.csdn.net/chen_yongbo/article/details/79759532