46: 1+2+3+。。。。。n
思路:用函数递归 ;
class Solution {
public:
int Sum_Solution(int n)
{
int sum=n;
return (n==0?sum:sum+Sum_Solution(n-1));
}
};
47、求两个数的和;(不能用四则运算)
把sum 看成是^的结果
把carry看成是进位;
while(num2)
{
int sum=num1^num2;
int carry=(num1&num2)<<1;
num1=sum;
num2=carry;
}
CODe:
class Solution {
public:
int Add(int num1, int num2)
{
if(!num2)return num1;
if(!num1)return num2;
while(num2)
{
int temp1=num1^num2;
int temp2=(num1&num2)<<1;
num1=temp1;
num2=temp2;
}
return num1;
}
};