0754.cpp (380B)
1 class Solution { 2 public: 3 int reachNumber(int target) const { 4 target = abs(target); 5 6 const long long n = ceil((sqrt(1 + 8.0 * target) - 1.0) / 2); 7 const long long sum = n * (n + 1) / 2; 8 9 if (sum == target) return n; 10 const long long res = sum - target; 11 12 if (res % 2 == 0) return n; 13 return n + (n % 2 == 1) + 1; 14 } 15 };