摘要:記一種簡單的的做法先討論邊界,若為最大值,返回然后對整數(shù)分奇偶兩種情況討論,偶數(shù)除以,奇數(shù)判斷是否后能被整除且不等于,若如此則,否則每次操作后計數(shù)器,循環(huán)結(jié)束后返回計數(shù)器值。
Problem
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
記一種簡單的iteration的做法:
先討論邊界case,若n為Integer最大值,返回32.
然后對整數(shù)n分奇偶兩種情況討論,偶數(shù)除以2,奇數(shù)判斷是否+1后能被4整除且n不等于3,若如此則+1,否則-1. 每次操作后計數(shù)器+1,循環(huán)結(jié)束后返回計數(shù)器值。
public class Solution { public int integerReplacement(int n) { if (n == Integer.MAX_VALUE) return 32; int count = 0; while (n != 1) { if (n%2 == 0) n/=2; else { if ((n+1)%4==0 && n!=3) n+=1; else n-=1; } count++; } return count; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/66036.html
摘要:復(fù)雜度思路利用位的操作。如果一個數(shù)是奇數(shù),那么末位的位一定是。對于偶數(shù),操作是直接除以。對于奇數(shù)的操作如果倒數(shù)第二位是,那么的操作比的操作能消掉更多的。還有一個的地方是,為了防止越界,可以將先轉(zhuǎn)換成。 LeetCode[397] Integer Replacement Given a positive integer n and you can do operations as fo...
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...
摘要:題目要求思路和代碼可以發(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 ...
摘要:子類通過實(shí)現(xiàn)方法或重寫其他父類的方法,從而提供了各種不同的具體操作,如判斷是否為某一個字符,判斷是否為數(shù)字字符,判斷是否為字符等。 showImg(https://segmentfault.com/img/bVbe1IW?w=300&h=300); 本文源地址:http://www.fullstackyang.com/...,轉(zhuǎn)發(fā)請注明該地址或segmentfault地址,謝謝! 最近...
閱讀 1297·2021-11-22 09:34
閱讀 2162·2021-10-08 10:18
閱讀 1724·2021-09-29 09:35
閱讀 2453·2019-08-29 17:20
閱讀 2137·2019-08-29 15:36
閱讀 3398·2019-08-29 13:52
閱讀 775·2019-08-29 12:29
閱讀 1183·2019-08-28 18:10