Today's Niuke == Base conversion=java keeps finding the remainder == consider the hexadecimal representation and positive and negative

Title description: Given a decimal number M, and the number N to be converted. Convert the decimal number M to the N system number
Input: 7,2
Return value: "111"

The topic is not difficult, you must consider the details, such as 10 with A, 11 with B, and be careful about the positive and negative of the number;

  • It is the process of constantly seeking the remainder, such as 17 to 3 digits,

  • 17%3=2, continue to do the dividend with the quotient of 17/3=5,

  • 5%3=2, continue to do the dividend with the quotient of 5/3=1,

  • 1%3=1, 1/3=0, the quotient ends at 0,

  • -Put all the remainders together, turn over 122 to be the ternary number => 2 * 3^0 + 2 * 3^1 + 1 * 3 ^2==17

  • char[] index = {'0','1','2','3','4','5','6','7','8','9','A', 'B','C','D','E','F'); to map the base

  • Take out the negative number and press the positive number operation

import java.util.*; 
public class Solution {
    
    
    /**
     * 进制转换
     * @param M int整型 给定整数
     * @param N int整型 转换到的进制
     * @return string字符串
     */
    public String solve (int M, int N) {
    
    
        // write code here
        StringBuffer str = new StringBuffer();
        char[] index = {
    
    '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        boolean flag = false;
        if(M <0){
    
    
            flag = true;
            M = -M;
        }
        while(M != 0){
    
    
            int remain = M % N;
            str.insert(0,index[remain]);
            M /= N;
        }
        if(flag) str.insert(0,'-');
        return str.toString();
    }
}

Guess you like

Origin blog.csdn.net/qq_45531729/article/details/110691622