I am working on the following question:
Given a positive integer n, and you can perform the following operations:If n is even, replace n with n / 2.If n is odd, you can replace n with n + 1 or n - 1.What is the minimum number of replacements needed for n to become 1?
Given a positive integer n, and you can perform the following operations:
What is the minimum number of replacements needed for n to become 1?
Here is the code I came up with:
class Solution { private: unordered_map<int, long long> count_num; public: int integerReplacement(int n) { count_num[1] = 0;count_num[2] = 1;count_num[3] = 2; if(!count_num.count(n)){ if(n%2){ count_num[n] = min( integerReplacement((n-1)/2), integerReplacement((n+1)/2) )+2; }else{ count_num[n] = integerReplacement(n/2) +1; } } return(count_num[n]); } };
When entering 2147483647, my code incorrectly outputs 33 instead of the correct answer, 32. Why is my code giving the wrong answer here?
, . , (2,147,483,647), , int, 32- , , , INT_MIN, 2,147,483,648. , , , , .
int
INT_MIN
,
integerReplacement((n+1)/2)
(n + 1)/2 . , , .
- , n , (n + 1)/2 (n/2) + 1 ( ). , ,
integerReplacement((n / 2) + 1)
, .
Source: https://habr.com/ru/post/1688745/More articles:Function const std :: function wraps non-constant operator () / mutable lambda - c ++strange code behavior (damaged draw) when using the native keyboard interrupt `int 09h` handler - assemblyHow to read haskell line - ioAny way to get std :: string_view from std :: ostringstream without copying? - c ++How exactly does the x86 LOOP instruction work? - assemblyThe jpeg image downloaded from iPhone to S3 is not readable. But working on photoshop - javascriptHow to declare a template function as a friend of a template nested class? - c ++Случай (ы), где выходной буфер не будет скрываться? - c++Erlang process names must be indispensable - erlangMatching two tables without relationship and without loop - sqlAll Articles