前天去面试的一道上机测试题(凭记忆写的题目)
Question:
给定输入整数(left( k
ight)),找到最小的自然数(nleft( {n ge 1}
ight)),使得下列公式成立:
[?1?2 cdots ?n = k]其中(?)可以是({
m{ + }})(加号)或者( - )(减号),输出(n)以及完整的表达式(可以不唯一)。
Example:
Input:12
Output:
7
-1+2+3+4+5+6-7=12
Solution:
#include<iostream> #include<vector> #include<math.h> using namespace std; int main() { cout<<"please input K:"<<endl; int k; cin>>k; int m=k; int n=1; while(n) { if(abs(k)%2==0 && (n*(n+1)/2)%2==0 && abs(k)<=(n*(n+1)/2)) break; else if(abs(k)%2==1 && (n*(n+1)/2)%2==1 && abs(k)<=(n*(n+1)/2)) break; else n++; } //下面开始计算每个数字前面的正负号 vector<int> data; vector<char> operators; for(int i=1;i<=n;i++) data.push_back(i); int max; for(int j=n;j>=1;j--) { max=(j*(j+1)/2); if((max-k) >= (2*data[j-1])) { operators.push_back('-'); k=k+data[j-1]; } else { operators.push_back('+'); k=k-data[j-1]; } } cout<<n<<endl; for(int p=0;p<n;p++) { cout<<operators[n-1-p]<<data[p]; } cout<<"="<<m<<endl; return 0; }