https://leetcode.com/problems/reach-a-number/description/
开始一直手残,,target=-target这行代码 写了,但是符号忘记带了。。
class Solution {
public:
long long cal( long long n, long long target ) {
long long ret = (n * n + n - 2 * target);
// cout << "ret:" << ret << endl;
return ret/2;
}
int reachNumber(int t) {
long long target = t;
if (target < 0) target = -target;
long long n = (-1 + sqrt( 1 + 8 * target )) / 2;
n--;
// cout << "pre n:" << n << "->" << cal(n, target) << endl;
while (cal(n, target) < 0) n++;
// cout << "bk n:" << n << endl;
int v = cal(n, target);
// cout << "v:" << v << endl;
if (v == 0) {
// cout << n << endl;
return n;
} else {
while (cal(n, target) % 2) {
n ++;
}
// cout << n << endl;
return n;
}
}
};