397. Integer Replacement
来源:互联网 发布:2级钢筋弯勾 算法 编辑:程序博客网 时间:2024/06/17 03:58
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
思路:以bit manipulation的方式来思考本题,
偶数没的说,奇数是加1还是减1需要考虑,看那个操作自后的bitCount更小(3是个特例)
因为偶数除以2可以更快的靠近1
奇数也是通过先转换成偶数除以2来得到消除某一位的效果
class Solution {public: int integerReplacement(int n) { if(n == 2147483647) return 32; int cnt = 0; while(n != 1) { if((n & 1) == 0) { n = (n >> 1); } else if(n == 3 || __builtin_popcount(n+1) > __builtin_popcount(n-1)) { n--; } else { n ++; } cnt++; } return cnt; }};
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
- tensorflow:图(Graph)的核心数据结构与通用函数(Utility function)
- <LeetCode>125.Valid Palindrome 验证回文字符串 Tag:string
- 黑马程序员 十二、反射机制
- ORACLE11g数据库字符集从ZHS16GBK转为UTF8
- 关于API
- 397. Integer Replacement
- Find Bottom Left Tree Value
- 实验 11 广播网络 OSPF 配置
- 十种排序算法总结(冒泡、插入、选择、希尔、归并、堆、快速,计数,桶,基数)
- webstorm支持es6与vue文件高亮
- 丑数。。。vector赋予空间,min函数
- 黑马程序员 十三、GUI
- 《探索C++多线程》:condition_variable源码(二)
- codeforces 798 D. Mike and distribution 二维贪心