Leetcode-397. Integer Replacement
来源:互联网 发布:深圳市软件行业协会 编辑:程序博客网 时间:2024/06/05 14:37
前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。这次比赛略无语,没想到前3题都可以用暴力解。
博客链接:mcf171的博客
——————————————————————————————
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这个题目我本来想着用dp做,但是没想到超时了。看了下discuss的说法,还是要位操作。Your runtime beats 55.55% of java submissions.
public class Solution { 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) { --n; } else { ++n; } ++c; } return c;}}
0 0
- 【Leetcode】397. Integer Replacement
- [leetcode]397. Integer Replacement
- LeetCode 397. Integer Replacement
- LeetCode 397. Integer Replacement
- LeetCode 397. Integer Replacement
- LeetCode 397. Integer Replacement
- LeetCode 397. Integer Replacement
- leetcode 397. Integer Replacement
- 【LeetCode】 397. Integer Replacement
- [LeetCode]397. Integer Replacement
- Leetcode-397. Integer Replacement
- [leetcode]397. Integer Replacement
- [leetcode]397. Integer Replacement
- LeetCode—397. Integer Replacement
- Leetcode 397. Integer Replacement[medium]
- 【Leetcode】397. Integer Replacement QuestionEditorial Solution【E】
- [leetcode] 397. Integer Replacement 解题报告
- Leetcode 397. Integer Replacement (Easy) (cpp)
- python: Matplotlib 教程
- 剑指offer之求数组中最小的n个数
- 设计模式之工厂模式
- 常用的8种排序算法总结
- HTTPS 与 HTTP2 协议分析
- Leetcode-397. Integer Replacement
- Dubbo Provider无法找到
- android 隐藏statusbar
- 任意多边形费马点&点群中位中心求解
- Jmeter函数之_StringFromFile
- Discuz!积分记录表pre_common_credit_log中operation字段含义一览
- js 定时执行
- 自留地:合理设置MTU,提升下载速度
- functional/vector