397. Integer Replacement
来源:互联网 发布:外星人设置灯光软件 编辑:程序博客网 时间:2024/06/08 21:49
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
orn - 1
.
What is the minimum number of replacements needed for n to become 1?
Example 1:
Input:8Output:3Explanation:8 -> 4 -> 2 -> 1
Example 2:
Input:7Output:4Explanation:7 -> 8 -> 4 -> 2 -> 1or7 -> 6 -> 3 -> 2 -> 1
分析如下:
https://discuss.leetcode.com/topic/58334/a-couple-of-java-solutions-with-explanations
结论:1.如果n是偶数 折半
2 如果n=3或者n-1中的1的位数比n+1中1的位数少那么n-1
3其余情况n+1
补充java方法: Integer.bitCount(int n) 返回n(二进制)中1的位数
>> 右移一位 <<左移一位 >>>忽略符号位右移一位, 用0补齐 此处需用这个! 否则会溢出2147483647
public int integerReplacement(int n) { int c = 0; while (n != 1) { if ((n & 1) == 0) { n >>>= 1; //这个地方要用n>>>1 如果用n=n/2 出现溢出问题 需要考虑? } else if (n == 3 || Integer.bitCount(n + 1) > Integer.bitCount(n - 1)) { --n; } else { ++n; } ++c; } return c;}
public int integerReplacement(int n) { int c = 0; while (n != 1) { if ((n & 1) == 0) { n >>>= 1; } else if (n == 3 || ((n >>> 1) & 1) == 0) { //留意后两位 奇数是最后一位是1 如果倒数第二位是0那么减1 使得1的位数更少 --n; } else { ++n; } ++c; } return c;}
0 0
- 【Leetcode】397. Integer Replacement
- 397. Integer Replacement
- [leetcode]397. Integer Replacement
- LeetCode 397. Integer Replacement
- LeetCode 397. Integer Replacement
- LeetCode 397. Integer Replacement
- 397. Integer Replacement
- LeetCode 397. Integer Replacement
- 397. Integer Replacement
- 397. Integer Replacement
- LeetCode 397. Integer Replacement
- leetcode 397. Integer Replacement
- 【LeetCode】 397. Integer Replacement
- [LeetCode]397. Integer Replacement
- 397. Integer Replacement
- 397. Integer Replacement
- 397. Integer Replacement
- Leetcode-397. Integer Replacement
- 文章标题 欧几里得求两数的最大公约数,最小公倍数。
- 新的征程
- HDU 5874 Friends and Enemies
- JDK简单安装
- 从JAVA行为参数化到 JAVA8 lamada,方法引用
- 397. Integer Replacement
- HDU 3555
- Redis系列----(二)redis中的数据结构类型
- Proteus 7.8 与 Keil 4 实现联调
- 几款开发、画原型图、前端框架分享
- 微信支付之获得openid(主动获得和被动获得)
- 2017年360公司校招Java研发笔试编程第一题
- 伽瑪校正
- 4385: [POI2015]Wilcze doły (单调队列)