任晟麒 • 2年前
#include<iostream>
#include<cmath>
// #include<locale>
using namespace std;
//做一个函数来把一个数字分解成2的幂次之和
string SumOfPowersOf2(int n){
string temp="";
int exponent;
while(n>0){
exponent=0;
while(pow(2,exponent)<=n)exponent++;
exponent--;
if(exponent==1)temp+="2+";
else temp+="2(" +to_string(exponent)+")+";
n-=pow(2,exponent);
}
temp.pop_back();
return temp;
}
//判断一个字符串有大于9这样的2位数字符串,并把这样的字符换成2的幂的和
void CharacterBetween3and9(string &s){
int length=s.length(),TempLength;
string temp;
for(int i=0;i<length-1;i++){
if(s[i]=='1'&&s[i+1]>='0'&&s[i+1]<='9'){
temp=SumOfPowersOf2(10+(int)s[i+1]-48);
TempLength=temp.length()-2;
s=s.substr(0,i)+temp+s.substr(i+2);
length+=TempLength;
i+=TempLength;
}
}
}
//判断一个字符串有大于2这样的1位数字符串,并把这样的字符换成2的幂的和
void CharacterGreaterThan2(string &s){
int length=s.length(),TempLength;
string temp;
for(int i=0;i<length-1;i++){
if(s[i]>'2'&&s[i]<='9'){
temp=SumOfPowersOf2((int)s[i]-48);
TempLength=temp.length()-1;
s=s.substr(0,i)+temp+s.substr(i+1);
length+=TempLength;
i+=TempLength;
}
}
}
int main(){
int n;
cin>>n;
string s=SumOfPowersOf2(n);
CharacterBetween3and9(s);
CharacterGreaterThan2(s);
CharacterGreaterThan2(s);
cout<<s;
return 0;
}
评论:
请先登录,才能进行评论