摘要:題目要求思路和代碼可以發(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 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思路和代碼
可以發(fā)現(xiàn)除二后所得到的結(jié)果一定優(yōu)于加減1。因此,如果當(dāng)前奇數(shù)除二為偶數(shù),則直接做除法,否則將當(dāng)前奇數(shù)加一再除以二,得到偶數(shù)的結(jié)果。
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; }
想要了解更多開發(fā)技術(shù),面試教程以及互聯(lián)網(wǎng)公司內(nèi)推,歡迎關(guān)注我的微信公眾號(hào)!將會(huì)不定期的發(fā)放福利哦~
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://specialneedsforspecialkids.com/yun/72427.html
摘要:復(fù)雜度思路利用位的操作。如果一個(gè)數(shù)是奇數(shù),那么末位的位一定是。對(duì)于偶數(shù),操作是直接除以。對(duì)于奇數(shù)的操作如果倒數(shù)第二位是,那么的操作比的操作能消掉更多的。還有一個(gè)的地方是,為了防止越界,可以將先轉(zhuǎn)換成。 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 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è)用例是,解決方法有兩種,第一就是首先把的二次冪都干掉,代碼如下 ...
閱讀 2579·2023-04-26 03:00
閱讀 1392·2021-10-12 10:12
閱讀 4190·2021-09-22 15:33
閱讀 2908·2021-09-22 15:06
閱讀 1530·2019-08-30 15:44
閱讀 2145·2019-08-30 13:59
閱讀 534·2019-08-30 11:24
閱讀 2407·2019-08-29 17:07