逛脉脉的时候,偶然看到一个数学题,觉得挺有意思,来兴致,做了个程序解答

解答:只计算了从2进制到10进制,可以设置
package com.seagate.zyproject;
public class CalSpecDigit {
/**
* 一个数字去掉首位是18,去掉末位是60,这个数字是多少?
* example(3进制,去首位18,去末位60)
* example(8进制,去首位296,去末位485)
* @param args
*/
public static void main(String[] args) {
calcMain(100,60);
}
public static void calcMain(int exceptFirst,int exceptLast){
String processValue = "";
int bit = 2,maxBit = 10;//初始二进制,最大十进制
while(bit <= maxBit){
processValue = judge(exceptFirst,bit,exceptLast);
if(!"".equals(processValue)){
System.out.println("The orgin number is "+processValue+" and the base digit is "+bit);
break;
}
bit++;
}
if("".equals(processValue))
System.out.println("No solution");
}
/**
* 根据所给去首位数及去末位数及进制位计算原始数
* @param exceptFirst
* @param bit
* @param exceptLast
* @return
*/
public static String judge(int exceptFirst,int bit,int exceptLast){
String result = "";
//将去末位数转为bit进制数。 这里只能用去末位数来推去首位数,反过来会相对麻烦,因为比如20200去首位会变成200,位数会不准
String lastToBit = calcPost(exceptLast,bit,calcBit(exceptLast,bit),"");
//循环bit进制最小到最大值
for(int i=0;i<bit;i++){
//根据lastToBit算出去首位数
String firstToBit = (lastToBit+i).substring(1, (lastToBit+i).length());
//将firstToBit转为十进制,判断是否与给出相等
if(bitToOct(firstToBit,bit) == exceptFirst){
result = lastToBit+i;
break;
}
}
return result;
}
/**
* 将原数按照进制位转换为十进制数
* @param dig
* @param base
* @return
*/
public static int bitToOct(String dig,int base){
int len = dig.length();
int result = 0;
for(int i=0;i<len;i++){
result += Integer.parseInt(String.valueOf(dig.charAt(i)))*Math.pow(base, len-1-i);
}
return result;
}
/**
* 根据进制计算原数的位数
* @param dig
* @param base
* @return
*/
public static int calcBit(int dig,int base){
if(dig < base){
return 1;
}else if(dig == base){
return 2;
}else{
int bit = 1;
while(Math.pow(base, bit-1) <= dig){
bit++;
}
return bit-1;
}
}
/**
* 将原数按照进制位转换为该进制的数
* @param dig
* @param base
* @param bit
* @param result
* @return
*/
public static String calcPost(int dig,int base,int bit,String result){
if(bit == 1){
return result += dig;
}else{
for(int i=1;i<base;i++){
if(Math.pow(base, bit-1)*i < dig){
if(i == base-1){
result += i;
return calcPost((int)(dig-Math.pow(base, bit-1)*i),base,bit-1,result);
}else{
continue;
}
}else if(Math.pow(base, bit-1)*i == dig){
result += i;
return calcPost(0,base,bit-1,result);
}else{
result += i-1;
return calcPost((int)(dig-Math.pow(base, bit-1)*(i-1)),base,bit-1,result);
}
}
return "0";
}
}
}



不一定是最好的,只是按照理解正向解答,如果有其他的解法可以评论告知一下。
这篇博客分享了一道有趣的数学问题,作者通过编写Java程序来求解。程序从2进制开始,遍历到10进制,寻找一个数字,它的去掉首位后等于18,去掉末位后等于60。最终,程序找到了符合条件的数字及其对应的进制。
1万+

被折叠的 条评论
为什么被折叠?



