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:
Input: 7
Output: 4
Explanation: 7 -> 8 -> 4 -> 2 -> 1 or 7 -> 6 -> 3 -> 2 -> 1
Tips: The infamous test with n=3 fails for that strategy because 11 ->10 -> 1 is better than 11 -> 100 -> 10 -> 1.
Solution:
If n is even, halve it.
If n=3 or n-1 has less 1"s than n+1,
decrement n. Otherwise, increment n.
Code:
public int integerReplacement(int n){ int count = 0; while(n!= 1){ if((n&1)==0){ n>>>=1; }else if(n ==3 ||((n >>>1) & 1 ==0){ --n; } else{ ++n; } count++; } return count; }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/66429.html
摘要:復雜度思路利用位的操作。如果一個數是奇數,那么末位的位一定是。對于偶數,操作是直接除以。對于奇數的操作如果倒數第二位是,那么的操作比的操作能消掉更多的。還有一個的地方是,為了防止越界,可以將先轉換成。 LeetCode[397] Integer Replacement Given a positive integer n and you can do operations as fo...
摘要:題目要求思路和代碼可以發現除二后所得到的結果一定優于加減。因此,如果當前奇數除二為偶數,則直接做除法,否則將當前奇數加一再除以二,得到偶數的結果。 題目要求 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...
Problem Given a positive integer n and you can do operations as follow: 1.If n is even, replace n with n/2.2.If n is odd, you can replace n with either n + 1 or n - 1. What is the minimum number of re...
摘要:記一種簡單的的做法先討論邊界,若為最大值,返回然后對整數分奇偶兩種情況討論,偶數除以,奇數判斷是否后能被整除且不等于,若如此則,否則每次操作后計數器,循環結束后返回計數器值。 Problem Given a positive integer n and you can do operations as follow: If n is even, replace n with n/2.I...
摘要:解題思路這題就是最基礎的遞歸運算題目,兩個選擇,一個是偶數,一個是奇數,偶數直接除操作,奇數變成左右兩個偶數繼續操作選擇操作最小的,注意有一個用例是,解決方法有兩種,第一就是首先把的二次冪都干掉,代碼如下 ...
閱讀 3513·2021-11-17 17:01
閱讀 3918·2021-11-08 13:12
閱讀 2477·2021-10-08 10:04
閱讀 687·2021-09-29 09:35
閱讀 1418·2021-09-26 10:12
閱讀 2021·2021-09-07 09:58
閱讀 1953·2019-08-30 15:55
閱讀 2134·2019-08-30 13:14