?LeetCode刷題實(shí)戰(zhàn)397:整數(shù)替換
Given a positive integer n, you can apply one of the following operations:
If n is even, replace n with n / 2.
If n is odd, replace n with either n + 1 or n - 1.
Return the minimum number of operations needed for n to become 1.

示例
給定一個(gè)正整數(shù) n ,你可以做如下操作:
如果 n 是偶數(shù),則用 n / 2替換 n 。
如果 n 是奇數(shù),則可以用 n + 1或n - 1替換 n 。
n 變?yōu)?1 所需的最小替換次數(shù)是多少?
解題
class Solution {
public:
int integerReplacement(long long n) {
if(n==1) return 0;
else if(n%2==0) return 1+integerReplacement(n/2);
else
{
long long m=n+1;
return 2+min(integerReplacement(m/2),integerReplacement((n-1)/2));
}
}
};
LeetCode1-380題匯總,希望對(duì)你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)381:O(1) 時(shí)間插入、刪除和獲取隨機(jī)元素
LeetCode刷題實(shí)戰(zhàn)382:鏈表隨機(jī)節(jié)點(diǎn)
LeetCode刷題實(shí)戰(zhàn)383:贖金信
LeetCode刷題實(shí)戰(zhàn)384:打亂數(shù)組
LeetCode刷題實(shí)戰(zhàn)385:迷你語(yǔ)法分析器
