题解 P1010 【幂次方】
greenlcat
·
·
题解
简单的位运算,看起来更清晰一些,用位运算分解加法项
#include<iostream>
#include<cstdio>
using namespace std;
void mici(int n){
if(n==1) return; //递归终止条件
if(n==0) { printf("0"); return ; } //递归终止条件
for(int i=16, mask=0x00008000, first=1; i>=1; i--){
if(mask&n){ //位运算进行分解
if(!first) printf("+"); //第一次不输出加号
printf("2");
if(i!=2) printf("("); //2^1时不需要括号
mici(i-1); //递归幂次
if(i!=2) printf(")"); //2^1时不需要括号
if(first) first=0; //控制加号的变量
}
mask>>=1; //掩码右移一位
}
}
int main(){
int n;
scanf("%d", &n);
mici(n);
return 0;
}