当前位置 : 主页 > 编程语言 > c++ >

正整数转的十六进制具体代码

来源:互联网 收集:自由互联 发布时间:2021-06-30
gistfile1.txt import java.util.Scanner;public class Main{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); while(sc.hasNext()) { int n = sc.nextInt(); System.out.println("标准答案:" + Integer.toHexString(n));
gistfile1.txt
import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        while(sc.hasNext()) {
            int n = sc.nextInt();

            System.out.println("标准答案:" + Integer.toHexString(n));
            System.out.println(hex(n));
            System.out.println(hex2(n));
        }
    }
    public static String hex(int n){
        StringBuffer str=new StringBuffer();
        for(;n>0;n/=16){
            switch(n%16) {
                case (10):
                    str.append("a");
                    break;
                case (11):
                    str.append("b");
                    break;
                case (12):
                    str.append("c");
                    break;
                case (13):
                    str.append("d");
                    break;
                case (14):
                    str.append("e");
                    break;
                case (15):
                    str.append("f");
                    break;
                default:
                    str.append(n % 16);
            }
        }
        return str.reverse().toString();
    }
    public static String hex2(int n){
        char[] chars={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
        StringBuilder str=new StringBuilder();
        for(;n>0;n/=16){
            str.append(chars[n%16]);
        }
        return str.reverse().toString();
    }

}
网友评论