hexadecimal conversion oj

Table of contents

1. Description of the topic

Second, problem-solving analysis

Third, the problem-solving code


1. Description of the topic

Second, problem-solving analysis

The conversion of decimal numbers uses the rolling and dividing method to obtain the remainder of each step; here are several situations to consider:

1. When the decimal number is a negative number, it is necessary to convert the decimal number into an integer at this time, but it is enough to add a negative sign to the result at the final output.

2. The output value is not only Arabic numerals, but also AF, which can be stored in an array and judge the remainder;

3. The final output of the result obtained by rolling and dividing needs to be reversed, because the calculated result is reversed; (I am saving it in the case of a string)

Third, the problem-solving code

import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        int n = sc.nextInt();
        int num1 = m;
        int flag = 1;
        //记录要被转进制的数是正数还是负数
        if(m < 0){
            flag = -1;
        }
        //为保证准确性,统一将这个数取为正整数
        int num = Math.abs(m);
        //使用辗转相除法进行运算,判断余数应该是取哪个字符
        String str = "0123456789ABCDEF";
        //用栈先保存起来,后序需要栈输出
        Stack<Character> s = new Stack<>();
        while(num != 0){
            s.push(str.charAt(num % n));
            num = num / n;
        }
        StringBuilder sb = new StringBuilder();
        if(flag == -1){
            sb.append('-');
        }
        while(!s.empty()){
            sb.append(s.pop());
        }
        if(num1 == 0){
            System.out.println(0);
        }else{
            System.out.println(sb.toString());
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_54773998/article/details/123454658