Integer Replacement
来源:互联网 发布:枪口动能计算器软件 编辑:程序博客网 时间:2024/05/14 15:04
What is not so obvious is what to do with odd numbers. One may think that you just need to remove as many 1's as possible to increase the evenness of the number. Wrong! 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 -> 111010
and 111011 -> 111100
remove the same number of 1's, but the second way is better.
So, we just need to remove as many 1's as possible, doing +1 in case of a tie? Not quite. The infamous test with n=3 fails for that strategy because 11 -> 10 -> 1
is better than 11 -> 100 -> 10 -> 1
. Fortunately, that's the only exception (or at least I can't think of any other, and there are none in the tests).
So the logic is:
- If
n
is even, halve it. - If
n=3
orn-1
has less 1's thann+1
, decrementn
. - Otherwise, increment
n
.
/* * 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:8Output:3Explanation:8 -> 4 -> 2 -> 1Example 2:Input:7Output:4Explanation:7 -> 8 -> 4 -> 2 -> 1or7 -> 6 -> 3 -> 2 -> 1 * * */public class Solution {public static void main(String[] args) {// TODO Auto-generated method stubSystem.out.println(Solution.integerReplacement(1234));}public static int integerReplacement(int n) { if(1 == n)return 0;int times = 0;while((n!=1){if((n&1) == 0){n >>>= 1;}else{if(n==3||Integer.bitCount(n+1)>Integer.bitCount(n-1))n--;elsen++;}times++;}return times;}}
0 0
- Integer Replacement
- Integer Replacement
- Integer Replacement
- 【Leetcode】397. Integer Replacement
- 397. Integer Replacement
- [leetcode]397. Integer Replacement
- LeetCode 397. Integer Replacement
- LeetCode 397. Integer Replacement
- LeetCode 397. Integer Replacement
- LeetCode 397 Integer Replacement
- [Leetcode] Integer Replacement
- 397. Integer Replacement
- LeetCode 397. Integer Replacement
- 397. Integer Replacement
- LeetCode[397] Integer Replacement
- LeetCode Integer Replacement
- Leetcode397: Integer Replacement
- 397. Integer Replacement
- HDU 5918 Sequence I kmp算法+虽然暴力也能过
- 2016华为校招上机试题2——洞穴逃生
- 3. Longest Substring Without Repeating Characters
- 51.[Python]使用multiprocessing进行多进程编程
- 51nod 1007 正整数分组(01背包)
- Integer Replacement
- C 重写power函数 递归与循环
- Visual Basic 总结
- 有关指针(1)
- Android Studio导入SlidingMenu库
- hdu1241油田
- webdriver+python 对三大浏览器的支持
- 视图总结
- 2063. 【2016.10.4NOIP普及模拟】Exam