397. Integer Replacement LeetCode Solution
In this guide, you will get 397. Integer Replacement LeetCode Solution with the best time and space complexity. The solution to Integer Replacement problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Integer Replacement solution in C++
- Integer Replacement solution in Java
- Integer Replacement solution in Python
- Additional Resources

Problem Statement of Integer Replacement
Given a positive integer n, you can apply one of the following operations:
If n is even, replace n with n / 2.
If n is odd, replace n with either n + 1 or n – 1.
Return the minimum number of operations needed for n to become 1.
Example 1:
Input: n = 8
Output: 3
Explanation: 8 -> 4 -> 2 -> 1
Example 2:
Input: n = 7
Output: 4
Explanation: 7 -> 8 -> 4 -> 2 -> 1
or 7 -> 6 -> 3 -> 2 -> 1
Example 3:
Input: n = 4
Output: 2
Constraints:
1 <= n <= 231 – 1
Complexity Analysis
- Time Complexity: O(\log n)
- Space Complexity: O(1)
397. Integer Replacement LeetCode Solution in C++
class Solution {
public:
int integerReplacement(long n) {
int ans = 0;
for (; n > 1; ++ans)
if (n % 2 == 0) // `n` ends in 0.
n >>= 1;
else if (n == 3 || (n >> 1 & 1) == 0) // `n` = 3 or ends in 0b01.
--n;
else // `n` ends in 0b11.
++n;
return ans;
}
};
/* code provided by PROGIEZ */
397. Integer Replacement LeetCode Solution in Java
class Solution {
public int integerReplacement(long n) {
int ans = 0;
for (; n > 1; ++ans)
if (n % 2 == 0) // `n` ends in 0.
n >>= 1;
else if (n == 3 || (n >> 1 & 1) == 0) // `n` = 3 or ends in 0b01.
--n;
else // `n` ends in 0b11.
++n;
return ans;
}
}
// code provided by PROGIEZ
397. Integer Replacement LeetCode Solution in Python
class Solution:
def integerReplacement(self, n: int) -> int:
ans = 0
while n > 1:
if n % 2 == 0: # `n` ends in 0.
n >>= 1
elif n == 3 or (n >> 1 & 1) == 0: # `n` = 3 or ends in 0b01.
n -= 1
else: # `n` ends in 0b11.
n += 1
ans += 1
return ans
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.