實作一個函數,對一個正整數n,算得到1需要的最少操作次數:如果n為偶數,将其除以2;如果n為奇數,可以加1或減1;一直處理下去。
例子:
ret=func(7);
ret=4,可以證明最少需要4次運算
n=7
n--6
n/2 3
n/2 2
n++1
要求:
實作函數(實作盡可能高效)int func(unsign int n);n為輸入,傳回最小的運算次數。
給出思路(文字描述),完成代碼,并分析你算法的時間複雜度。
請列舉測試方法和思路。
--------------------------------------------------------------------------------------------
首先已知:
f(1)=0
f(2)=1
f(3)=2
f(4)=2
然後是偶數的話就除2, 是奇數的話(必須不為3)除4餘1的話則減1,餘3的話就加1.
1 #include<iostream>
2 using namespace std;
3 int func(unsigned n) {
4 int count=0;
5 if(n<2) return 0;
6 if(n==2) return 1;
7 if(n==3) return 2;
8 while(n != 1) {
9 if(n%2==0) {
10 n/=2;
11 count++;
12 }else {
13 if(n%4==1){
14 n--;
15 count++;
16 }else {
17 n++;
18 count++;
19 }
20 }
21 }
22 return count;
23 }
24
25 int main() {
26 int in=0;
27 cin>>in;
28 cout<<func(in)<<endl;
29 }
轉載于:https://www.cnblogs.com/sanfeng/p/4380260.html