正整数n,算得到1需要的最少操作次数

实现一个函数对一个正整数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 }

 

posted @ 2015-03-31 11:05  叁疯  阅读(280)  评论(0编辑  收藏  举报