LeetCode Integer Replacement
2017-01-11 12:51
344 查看
原题链接在这里:https://leetcode.com/problems/integer-replacement/
题目:
Given a positive integer n and you can do operations as follow:
If n is even, replace n with
If n is odd, you can replace n with either
What is the minimum number of replacements needed for n to become 1?
Example 1:
Example 2:
题解:
n是偶数时除以2是确定的,问题是n是奇数时+1 还是 -1. 尽可能的消除1 bit, +1 或 -1后哪个1 bit少就选哪个.
若+1或-1后1 bit相同,那么除了3特殊情况下其他都选+1.
Time Complexity: O(1), int最多32位,最多64次操作.
Space: O(1).
AC Java:
除了3特例之外,看n的倒数第二位,若是1, n++, 若是0, n--.
Time Complexity: O(1). Space: O(1).
AC Java:
Reference: https://discuss.leetcode.com/topic/58334/a-couple-of-java-solutions-with-explanations
题目:
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 + 1or
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
题解:
n是偶数时除以2是确定的,问题是n是奇数时+1 还是 -1. 尽可能的消除1 bit, +1 或 -1后哪个1 bit少就选哪个.
若+1或-1后1 bit相同,那么除了3特殊情况下其他都选+1.
Time Complexity: O(1), int最多32位,最多64次操作.
Space: O(1).
AC Java:
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 >>>= 1; 7 }else if(n == 3 || Integer.bitCount(n+1) > Integer.bitCount(n-1)){ 8 n--; 9 }else{ 10 n++; 11 } 12 count++; 13 } 14 return count; 15 } 16 }
除了3特例之外,看n的倒数第二位,若是1, n++, 若是0, n--.
Time Complexity: O(1). Space: O(1).
AC Java:
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 >>>= 1; 7 }else if(n == 3 || ((n >>> 1) & 1) == 0){ 8 n--; 9 }else{ 10 n++; 11 } 12 count++; 13 } 14 return count; 15 } 16 }
Reference: https://discuss.leetcode.com/topic/58334/a-couple-of-java-solutions-with-explanations
相关文章推荐
- LeetCode Integer Replacement
- Leetcode (397) Integer Replacement
- (LeetCode)Integer Replacement --- 整数替换
- Leetcode 397. Integer Replacement (Easy) (cpp)
- LeetCode-Integer Replacement
- Leetcode Integer Replacement
- Leetcode: Integer Replacement
- [LeetCode] Integer Replacement 整数替换
- LeetCode 397 Integer Replacement
- leetcode Roman to Integer
- Leetcode:Reverse Integer
- LeetCode_String to Integer (atoi)
- LeetCode 13. Roman to Integer和12. Integer to Roman
- 蜗牛慢慢爬 LeetCode 8. String to Integer (atoi) [Difficulty: Medium]
- Leetcode - Reverse Integer
- 【LeetCode 13】 Roman to Integer
- LeetCode(8) String To Integer(atoi)
- [C++]LeetCode 8:String to Integer (atoi)(字符串转int)
- LeetCode_Roman to Integer
- Leetcode-12. Integer to Roman