实现两个非负整数相乘

    题目:《EPI》P181

    实现两个非负整数相乘,只允许位操作,不允许自增或自减符号。

    提示:左移一位相当于乘以2,右移一位相当于除以2.

unsigned int Add(unsigned int x, unsigned int y)
{
	if (y == 0)
		return x;
	unsigned int sum = x^y;
	unsigned int carry = (x&y) << 1;
	return Add(sum, carry);
}

unsigned int multiply(const unsigned int &a, const unsigned int &b)
{
	if (a == 0 || b == 0)
		return 0;
	unsigned int sum = 0, k = 1,atemp=a;
	while (k)
	{
		if (b&k)
		{
			sum = Add(atemp, sum);
		}		
		atemp <<= 1;//左移一位相当于乘以2
		k <<= 1;
	}
	return sum;
}


你可能感兴趣的:(程序员面试题)