<pre name="code" class="java">/**
* 十进制转三进制,只实现了整数部分
* @author CaoChenMiao
*
*/
public class TentoSan {
private int TtS(int inNum, int index) throws Exception {
if(inNum < index || index <= 1){
throw new Exception("不支持的运算");
}
String outNum = "";
int maxIndex = getMaxIndex(inNum, index, 0, 0);
int[] result = new int[maxIndex];
/*方法一:写的时候没有意识到余数就是所需要的值 ╮(╯▽╰)╭
* for (int i = 0; i < maxIndex; i++) {
int pow_ = (int)Math.pow(index, maxIndex-1-i);
if(inNum - pow_ >= 0){
result[i] = inNum/pow_;
inNum -= pow_ * result[i];
}else if(i != maxIndex-1){
result[i] = 0;
}else{
result[i] = inNum;
}
}*/
//方法二: 简单,便捷
for (int i = 0; i < maxIndex; i++) {
result[i] = inNum % index;
inNum = inNum / index;
}
for (int i = 0; i < result.length; i++) {
outNum += result[i];
}
return Integer.parseInt(outNum);
}
/**
* 计算最高位数
* inNum:输入的数字
* index:进制数
* countNum:累积次数
* total:累积和
*/
private int getMaxIndex(int inNum, int index, int countNum, int total){
int countTotal = total;
int count = countNum;
int pow_ = (int)Math.pow(index, ++countTotal);
while(inNum - pow_ >= 0){
inNum-=pow_;
count+=pow_;
if(inNum - count < 0){
break;
}
return getMaxIndex(inNum, index, count, countTotal);
}
return countTotal+1;
}
public static void main(String[] args) throws Exception {
TentoSan ts = new TentoSan();
System.out.println(ts.TtS(100,3));
//输出结果:10201
//小结:有返回值的递归函数注意return自身
}
}
Java十进制转三进制
原文作者:进制转换
原文地址: https://blog.csdn.net/qq_26858883/article/details/44779505
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://blog.csdn.net/qq_26858883/article/details/44779505
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。