剑指offer 47、48:求1+2+3+...+n 、不用加减乘除做加法

47.题目描述
求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
思路:通过逻辑运算,达到控制操作的效果。

class Solution {
public:
    int Sum_Solution(int n) {
        int sum=0;
        n && (sum=Sum_Solution(n-1) + n);//n控制累加操作
        return sum;
    }
};
# -*- coding:utf-8 -*-
class Solution:
    def Sum_Solution(self, n):
        return n and self.Sum_Solution(n-1)+n
        # write code here

python 中 and 返回值:a and b a为真 则 返回 b,a为假则返回a,即返回可进行运算的最后一位。
1 and 2 and 3 返回3
0 and 2 and 3 返回 0
1 and 0 and 3 返回0
1 and 2 and 0返回0
or 返回第一个为真的,都为假则返回0
1 or 2 返回 1
0 or 2 返回 2
0 or 0 返回 0
48.题目描述
写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。
思路:相加不进位:1+1=0,1+0=1,0+0=0 ==》异或操作
进位:1+1=1,1+0=0,0+0=0 ==》与操作 然后左移一位

class Solution {
public:
    int Add(int num1, int num2)
    {        
        int sum=0,carry=0;
        while(num1)
        {
            sum=num1^num2;
            carry=num1 & num2;
            num1=carry<<1;
            num2=sum;
        }
        return num2;
    }
};
# -*- coding:utf-8 -*-
class Solution:
    def Add(self, num1, num2):
        while num1:
            num1,num2=((num1 & num2)<<1) & 0xffffffff ,(num1^num2)&0xffffffff
        return num2 if num2 <=0x7fffffff else ~(num2^0xffffffff)
        # write code here

猜你喜欢

转载自blog.csdn.net/zd_nupt/article/details/81479709
今日推荐