Leetcode: Integer Replacement
2016-12-01 12:31
435 查看
Given a positive integer n and you can do operations as follow: If n is even, replace n with n/2. If n is odd, you can replace n with either n + 1 or n - 1. What is the minimum number of replacements needed for n to become 1? Example 1: Input: 8 Output: 3 Explanation: 8 -> 4 -> 2 -> 1 Example 2: Input: 7 Output: 4 Explanation: 7 -> 8 -> 4 -> 2 -> 1 or 7 -> 6 -> 3 -> 2 -> 1
Refer to: https://discuss.leetcode.com/topic/58334/a-couple-of-java-solutions-with-explanations/2
When to add 1 instead of minus 1, here is an example:
Look at this example:
111011 -> 111010 -> 11101 -> 11100 -> 1110 -> 111 -> 1000 -> 100 -> 10 -> 1
And yet, this is not the best way because
111011 -> 111100 -> 11110 -> 1111 -> 10000 -> 1000 -> 100 -> 10 -> 1
See? Both
111011 -> 111010and
111011 -> 111100remove the same number of 1's, but the second way is better.
Indeed, if a number ends with 01, then certainly decrementing is the way to go. Otherwise, if it ends with 11, then certainly incrementing is at least as good as decrementing (
*011 -> *010 / *100) or even better (if there are three or more 1's). This leads to the following solution:
So the logic is:
If
nis even, halve it.
If
n=3or
n ends with "01", decrease n
Otherwise, increment
n.(ends with "11", "111" or even more "1111")
1 public class Solution { 2 public int integerReplacement(int n) { 3 int count = 0; 4 while (n != 1) { 5 if ((n & 1) == 0) 6 n = n >>> 1; 7 else if (n==3 || (n & 0b11) == 1) 8 n--; 9 else n++; 10 count++; 11 } 12 return count; 13 } 14 }
Another logic is:
So the logic is:
If
nis even, halve it.
If
n=3or
n-1has less 1's than
n+1, decrement
n.
Otherwise, increment
n.
1 public int integerReplacement(int n) { 2 int c = 0; 3 while (n != 1) { 4 if ((n & 1) == 0) { 5 n >>>= 1; 6 } else if (n == 3 || Integer.bitCount(n + 1) > Integer.bitCount(n - 1)) { 7 --n; 8 } else { 9 ++n; 10 } 11 ++c; 12 } 13 return c; 14 }
相关文章推荐
- Leetcode 397. Integer Replacement (Easy) (cpp)
- LeetCode-Integer Replacement
- Leetcode Integer Replacement
- [LeetCode] Integer Replacement 整数替换
- LeetCode 397 Integer Replacement
- Leetcode (397) Integer Replacement
- LeetCode Integer Replacement
- LeetCode Integer Replacement
- (LeetCode)Integer Replacement --- 整数替换
- [LeetCode] String to Integer (atoi)
- LeetCode - Roman to Integer
- leetcode 7. Reverse Integer
- LeetCode 8. String to Integer (atoi)
- [Week 1]【Leetcode】Reverse Integer(逆序问题)
- LeetCode-String to Integer (atoi)-状态机简单搜索
- [LeetCode]题解(python):012-Integer to Roman
- Leetcode -- Roman to Integer
- leetcode Reverse Integer 2.2 难度系数2
- LeetCode Roman to Integer
- LeetCode小白菜笔记[4]:Roman to Integer