371. Sum of Two Integers

来源:互联网 发布:滑板淘宝 编辑:程序博客网 时间:2024/05/19 03:46

Problem description

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example:

Given a = 1 and b = 2, return 3.

题目描述

计算两个整数a与b的和,但是你不能使用+、-运算

例子

输入a = 1,b = 2,返回3
链接:https://leetcode.com/problems/sum-of-two-integers/

解题思路

模拟计算机二进制形式的计算加法,采用异或、与、移位运算
public class Solution {    public int getSum(int a, int b) {        int c = a ^ b;int d = (a & b) << 1;while(d != 0){a = d;b = c;c = a ^ b;d = (a & b) << 1; }return c;    }}
此外java还自带的Math.addExact(a, b)函数,python的sum()函数都可以用来ac这道题,不过不是正途。


0 0