对正整数,算得到1需要操作的次数

题目:

实现一个函数,对一个正整数n,算得到1需要的最少操作次数。
操作规则为:如果n为偶数,将其除以2;如果n为奇数,可以加1或减1;一直处理下去。
例子:
func(7) = 4,可以证明最少需要4次运算
n = 7
n-1 6
n/2 3
n-1 2
n/2 1
要求:实现函数(实现尽可能高效) int func(unsign int n);n为输入,返回最小的运算次数。
给出思路(文字描述),完成代码,并分析你算法的时间复杂度。

int func(unsign int n)
{
	if (n == 1)
	{
		return 0;
	}
	if (n%2 == 0)
	{
		return 1 + func(n/2);
	}
	int x = func(n+1);
	int y = func(n-1);
	if (x > y)
	{
		return y + 1;
	}
	else
	{
		return x + 1;
	}
}

假设n表示成二进制有x bit,可以看出计算复杂度为O(2^x),也就是O(n)。

更多解决方案见:

http://hi.baidu.com/mianshiti/blog/item/e4487db6ac2afac537d3ca27.html

原文地址:https://www.cnblogs.com/dartagnan/p/2196854.html