标签:style blog color io os ar sp div on
例子:
func(7) = 4,可以证明最少需要4次运算
n = 7
n-1 6
n/2 3
n-1 2
n/2 1
要求:实现函数(实现尽可能高效) int func(unsign int n);n为输入,返回最小的运算次数。给出思路(文字描述),完成代码,并分析你算法的时间复杂度。
1 #include<iostream> 2 using namespace std; 3 4 int func(unsigned int n){ 5 6 int res = 0; 7 while(n != 1){ 8 if(n & 1 == 0) {//末尾为0,直接右移 9 n /= 2; 10 res++; 11 } 12 else if( n & 7 == 7) { 13 //末3位为1加一(因为序列内部的11收支平衡;序列头部的111收支平衡;更长的序列正收益更大) 14 n++; 15 n /= 8; 16 res += 4; 17 } else{ 18 //末3位不全为1则减一(序列内部的11收支平衡,加一减一均可) 19 n--; 20 n /= 2; 21 res += 2; //一次自减一次右移 22 } 23 } 24 return res; 25 } 26 27 int main(){ 28 printf("%d\n", func(100)); 29 return 0; 30 }
标签:style blog color io os ar sp div on
原文地址:http://www.cnblogs.com/wanghui390/p/4013753.html