《算法通关村—进制转换问题处理模板》
先来一个题热热身
504. 七进制数
给定一个整数 num
,将其转化为 7 进制,并以字符串形式输出。
示例 1:
输入: num = 100
输出: "202"
示例 2:
输入: num = -7
输出: "-10"
提示:
-107 <= num <= 107
题解
解决这种问题都是通过取模,然后除以要转的进制位,循环直到数据为0,然后倒序输出就好,最后就是要注意0,和正负的问题了。
class Solution {public String convertToBase7(int num) {StringBuffer sb = new StringBuffer();boolean sign = num<0;if(num == 0){return "0";}while(num != 0){sb.append(Math.abs(num%7) + "");num/=7;}if(sign){sb.append("-");}return sb.reverse().toString();}}
进制处理模板
处理的方法其实差不多的。
public class NumConversionUtil {/*** 进制转换工具类* @param num* @param scale* @return*/public static String numConversionUtil(int num , int scale){String[] nums = new String[] {"1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};boolean sign = num < 0;if(sign){num*=-1;}StringBuffer sb = new StringBuffer();int temp = 0;if(num == 0){return "0";}while(num != 0){temp = num % scale;sb.append(temp + "");num/=scale;}if(sign){sb.append("-");}return sb.reverse().toString();}public static void main(String[] args) {System.out.println(numConversionUtil(0,2));}
}