To prove safety Offer - face questions 65. Math to do without the addition (bit operation, depending oh)

1. Topic

A write function, and the sum of two integers, the function may not be used in vivo requires “+”、“-”、“*”、“/”four operational sign.

示例:
输入: a = 1, b = 1
输出: 2
 
提示:
a, b 均可能是负数或 0
结果不会溢出 32 位整数

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/bu-yong-jia-jian-cheng-chu-zuo-jia-fa-lcof
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

2. bit computing

  • We will a+b, split into an addition without carry a^b, carry(a&b)<<1
  • Carry to the end 0

Cycle wording

class Solution {
public:
    int add(int a, int b) {
    	int sum;
        while(b)
        {
        	sum = a^b;//不带进位的加法
        	b = (unsigned int)(a&b)<<1;//b是进位
        	a = sum;//a是和,当b进位为0时,结束
        }
        return a;
    }
};

Recursive wording

class Solution {
public:
    int add(int a, int b) {
        if(b == 0)
        	return a;
        return add(a^b, (unsigned int)(a&b)<<1);
    }
};

Here Insert Picture Description

Published 630 original articles · won praise 492 · Views 140,000 +

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/104303944