机试题,设计一个函数,如下功能。。。
求老鸟指点算法
设计一个函数func(X);
判断X是偶数的话,X除以2,;判断到X是奇数的话,X可以加1,或者减1; 目标是求出X得到1为止的最少运算量;
例如:
func(7)
7 -> 6
6 -> 3
3 -> 2
2 -> 1
[解决办法]
#include <iostream>using namespace std;int func(int x);int main(){ int i; cout << "输入一个数字: "; cin >> i; if (!cin || i < 1) { cout << "输入非法,程序退出!\n"; return -1; } cout << "最小步数: " << func(i) << endl; return 0;}int func(int x){ int m; int count = 0; while (x != 1) { if (x % 2 == 0) { cout << x << " --> " << x / 2 << endl; x /= 2; } else { m = 2; while (m < x) m *= 2; if (x - 1 == m / 2) //先判断下边界 { cout << x << " --> " << x - 1 << endl; x--; } else if (x + 1 == m) //再判断上边界 { cout << x << " --> " << x + 1 << endl; x++; } else { cout << x << " --> " << x - 1 << endl; x--; } } count++; } return count;}
[解决办法]
[code=C/C++][/code]
//add.cpp
#include <iostream>
#include <conio.h>
using namespace std;
#define min(a,b) ((a)<(b))?(a):(b)
static int count = 0;
int func(int x)
{
if (1 == x)
{
//if (count == 0)
// return 0;//运算量为0
//else
return 0;
}
else
{
//count++;
if ( 0 == x%2 )
return func(x/2)+1;//
else
{
return min(func(x-1)+1,func(x+1)+1);
}
}
}
int main()
{
int x = 7;
int res = func(x);
cout<<res<<endl;
return 0;
}