乐视笔试-蚱蜢问题代码
贪心策略,复杂度O(1),很多出现只过17%的,很可能没有对x < 0作处理,如果不对x < 0作处理,就是17%。
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int x;
while(cin >> x) {
if(x < 0) x = -x;
if(x < 2) cout << x << endl;
else if(x == 2) cout << "3" << endl;
else {
int num = sqrt(double(2 * x + 1 / 4)) - 1 / 2;
while((num * num + num) / 2 < x || ((num * num + num) / 2 - x) % 2) ++num;
cout << num << endl;
}
}
return 0;
}
查看20道真题和解析