问题描述
任何一个正整数都可以用2的幂次方表示。例如:
137=27+23+20
同时约定方次用括号来表示,即ab 可表示为a(b)。
由此可知,137可表示为:
2(7)+2(3)+2(0)
进一步:7= 22+2+20 (21用2表示)
3=2+20
所以最后137可表示为:
2(2(2)+2+2(0))+2(2+2(0))+2(0)
又如:
1315=210 +28 +25 +2+1
所以1315最后可表示为:
2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)
输入格式
输入包含一个正整数N(N<=20000),为要求分解的整数。
输出格式
程序输出包含一行字符串,为符合约定的n的0,2表示(在表示中不能有空格)
针对此题,我们通过递归的方式来求解。这题的递归实际上可以分两部分进行。
1.递归分解2的幂次方。
2.递归输出表达式。
对于第一步递归,我们首先对待分解的数字进行以2为底的对数运算,舍去结果的小数部分,即为分解得到的第一个幂,再进行递归运算,得出所有分解的结果。
public static void split(int num)
{
if(num==0)
return ;
//换底公式:以2 为底进行对数运算
double a=Math.log(num)/Math.log(2.0);
int b=(int) a;
//System.out.println(b+" "); //输出查看分解的值
num-=Math.pow(2, b);//将剩下未分解的值进行递归分解
split(num);
}
这样我们就得到了分解之后的幂值。由于题目要求的输出格式——将约定方次用括号来表示,观察可以发现,整个式子中的元素全部由为0,1,2次幂组成,即2(0),2,2(2)来表示。我们将0,1,2次幂对应的表示以键值对的形式保存。
HashMap map=new HashMap();
map.put(0, "2(0)");
map.put(1, "2");
map.put(2, "2(2)");
现在便开始实现第二步递归。这一步递归主要是将幂值大于2的次数分解。分解出来的值为两部分,幂数b和待分解的余数num。
这里我们要做一个判断。如果此时待分解的余数num为0且幂值b为0或1或2,那么我们打印的格式就是直接在字符串后加上相对应的表达式。num不为0,说明要进一步分解(包括幂和余数),进一步分解时依然要将幂值为0或1或2的情况特殊考虑(直接加在打印值后面),否则打印格式就需要加上 2(),最后再加上余数的分解值。
public static String style(int num)
{
if(num==0) return ""; //为0时递归结束
String str="";//存放打印值
double a=Math.log(num)/Math.log(2.0);
int b=(int) a;//num分解后得到的幂
num-=Math.pow(2, b);//待分解的余数
if (num==0 && (b==0 || b==1 || b==2))
str+=map.get(b);
else
if(b==0 || b==1 || b==2)
str+=map.get(b)+"+"+style(num);
else
str+="2("+style(b)+")"+"+"+style(num);
//去除+号
if(str.endsWith("+"))
return str.substring(0, str.length()-1);
return str;
}
上述函数的调用就添加在第一个递归函数中便可。对于整体思路清晰者,其实可以把两个函数合并放在一起写。
当然,个人觉得,分开成两个函数写便于理解
对于递归问题需要保持清晰的思路,对整体的把握,否则容易把自己递晕,害…
完整的代码如下
public class 幂方分解 {
static HashMap map=new HashMap();
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
map.put(0, "2(0)");
map.put(1, "2");
map.put(2, "2(2)");
System.out.print(style(n));
}
public static void split(int num)
{
if(num==0)
return ;
//换底公式:以2 为底进行对数运算
double a=Math.log(num)/Math.log(2.0);
int b=(int) a;
num-=Math.pow(2, b);//将剩下未分解的值进行递归分解
if(b>2)
System.out.print("2("+style(b)+")");
else
System.out.print("+"+style(b));
split(num);
}
public static String style(int num)
{
if(num==0) return ""; //为0时递归结束
String str="";//存放打印值
double a=Math.log(num)/Math.log(2.0);
int b=(int) a;//num分解后得到的幂
num-=Math.pow(2, b);//待分解的余数
if (num==0 && (b==0 || b==1 || b==2))
str+=map.get(b);
else
if(b==0 || b==1 || b==2)
str+=map.get(b)+"+"+style(num);
else
str+="2("+style(b)+")"+"+"+style(num);
//去除+号
if(str.endsWith("+"))
return str.substring(0, str.length()-1);
return str;
}
}
关于蓝桥杯其他题解的代码可以看看→→GitHub传送门