leetcode 397. Integer Replacement 二分查找
来源:互联网 发布:java反射获取方法私有 编辑:程序博客网 时间:2024/06/02 04:41
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:
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
题意很简单,就是做一个简单的DFS深度优先遍历查找,
注意要使用long long数据类型,使用int可能超时
代码如下:
#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>using namespace std;class Solution {public: int integerReplacement(int n) { if (n <= 1) return 0; else return (int)getRes(n); } int getRes(long long n) { if (n == 1) return 0; else { if (n % 2 == 0) return getRes(n / 2) + 1; else { int a = getRes(n - 1) + 1; int b = getRes(n + 1) + 1; return min(a, b); } } }};
阅读全文
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
- Leetcode 397. Integer Replacement[medium]
- 【Leetcode】397. Integer Replacement QuestionEditorial Solution【E】
- [leetcode] 397. Integer Replacement 解题报告
- 工信部发2016年中国互联网企业100强名单
- Web 基础
- SuperMap iDesktop常见问题解答集锦(十一)
- springboot获取项目跟目录
- JS判断浏览器IE6、IE7、IE8、IE9、IE10、IE11、Chrome、Firefox、Safari、Opera方法,亲测可用
- leetcode 397. Integer Replacement 二分查找
- i++与++i的左值右值问题
- 4.redis常用命令
- hdoj 1022 Train Problem I (第一次接触栈)
- 并查集--Union_Find
- Null 传导运算符
- Failed to resolve: com.android.support:appcompat-v7:27.0.1问题解决
- 前端性能优化
- Servlet 生命周期