摘要:復(fù)雜度思路利用位的操作。如果一個(gè)數(shù)是奇數(shù),那么末位的位一定是。對(duì)于偶數(shù),操作是直接除以。對(duì)于奇數(shù)的操作如果倒數(shù)第二位是,那么的操作比的操作能消掉更多的。還有一個(gè)的地方是,為了防止越界,可以將先轉(zhuǎn)換成。
LeetCode[397] Integer Replacement
Bit ManipulationGiven 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
復(fù)雜度
O(1) ?, O(1)
思路
利用bit位的操作。如果這個(gè)數(shù)偶數(shù),那么末位的bit位一定是0。如果一個(gè)數(shù)是奇數(shù),那么末位的bit位一定是1。對(duì)于偶數(shù),操作是直接除以2。
對(duì)于奇數(shù)的操作:
如果倒數(shù)第二位是0,那么n-1的操作比n+1的操作能消掉更多的1。
1001 + 1 = 1010
1001 - 1 = 1000
如果倒數(shù)第二位是1,那么n+1的操作能比n-1的操作消掉更多的1。
1011 + 1 = 1100
1111 + 1 = 10000
還有一個(gè)tricky的地方是,為了防止integer越界,可以將n先轉(zhuǎn)換成long。long N = n;這樣的處理。
代碼
同樣是從別的地方看到比較好的代碼;
public int integerReplacement(int n) { // 處理大數(shù)據(jù)的時(shí)候tricky part, 用Long來代替int數(shù)據(jù) long N = n; int count = 0; while(N != 1) { if(N % 2 == 0) { N = N >> 1; } else { // corner case; if(N == 3) { count += 2; break; } N = (N & 2) == 2 ? N + 1 : N - 1; } count ++; } return count; }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://specialneedsforspecialkids.com/yun/65213.html
摘要:題目要求思路和代碼可以發(fā)現(xiàn)除二后所得到的結(jié)果一定優(yōu)于加減。因此,如果當(dāng)前奇數(shù)除二為偶數(shù),則直接做除法,否則將當(dāng)前奇數(shù)加一再除以二,得到偶數(shù)的結(jié)果。 題目要求 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...
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 ...
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...
摘要:記一種簡(jiǎn)單的的做法先討論邊界,若為最大值,返回然后對(duì)整數(shù)分奇偶兩種情況討論,偶數(shù)除以,奇數(shù)判斷是否后能被整除且不等于,若如此則,否則每次操作后計(jì)數(shù)器,循環(huán)結(jié)束后返回計(jì)數(shù)器值。 Problem Given a positive integer n and you can do operations as follow: If n is even, replace n with n/2.I...
摘要:解題思路這題就是最基礎(chǔ)的遞歸運(yùn)算題目,兩個(gè)選擇,一個(gè)是偶數(shù),一個(gè)是奇數(shù),偶數(shù)直接除操作,奇數(shù)變成左右兩個(gè)偶數(shù)繼續(xù)操作選擇操作最小的,注意有一個(gè)用例是,解決方法有兩種,第一就是首先把的二次冪都干掉,代碼如下 ...
閱讀 1811·2021-10-09 09:44
閱讀 3382·2021-09-28 09:35
閱讀 1372·2021-09-01 10:31
閱讀 1658·2019-08-30 15:55
閱讀 2697·2019-08-30 15:54
閱讀 923·2019-08-29 17:07
閱讀 1372·2019-08-29 15:04
閱讀 2001·2019-08-26 13:56