剑指offer-64

1+2+3+4+。。。+n=?,不需使用四则运算和关键字,条件判断语句

解法一:用位运算模拟加法?用递归模拟循环?还是要用关键字,不符合要求

A^b=c,a&b=d,d=d<<1,

If c&d>0 继续进位

Else return c^d

解法一:不符合要求
unsigned int addPos(unsigned int a, unsigned int b)
{
	unsigned int c = a&b;
	c = c << 1;
	unsigned int d = a^b;
	if ((c&d) > 0)
		return addPos((c&d) << 1, c^d);
	else
		return c^d;
}
void addSum(unsigned int& ret, unsigned int a)
{
	if (a <= 0) return;
	ret = addPos(ret, a);
	return addSum(ret, a - 1);
}
unsigned int Sum_Solution5(unsigned int n)
{
	if (n <= 0) return 0;
	if (n == 1) return n;
	unsigned int ret = n;
	addSum(ret, n - 1);
	return ret;
}

 

你可能感兴趣的:(剑指)