LeetCode 371 Sum of Two Integers

Posted SillyVicky

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 371 Sum of Two Integers相关的知识,希望对你有一定的参考价值。

Problem:

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

Summary:

不使用+和-符号,计算两个整型数之和。

Analysis:

XOR相当于二进制数的无进位加法。进位位由两数&运算后左移一位确定。

Example:

用此方法计算5 + 3:

1、无进位结果:101 ^ 011 = 110  进位:101 & 011 = 001  左移:001 << 1 = 010

2、将进位与原结果相加:110 ^ 010 = 100  进位:110 & 010 = 010  左移:010 << 1 = 100

3、将进位与原结果相加:100 ^ 100 = 000  进位:100 & 100 = 100  左移:100 << 1 = 1000

4、将进位与原结果相加:000 ^ 1000 = 1000  进位:000 & 1000 = 0000

故:和为10002 = 8

 1 class Solution {
 2 public:
 3     int getSum(int a, int b) {
 4         while (b) {
 5             int carry = (a & b) << 1;
 6             a = a ^ b;
 7             b = carry;
 8         }
 9         
10         return a;
11     }
12 };

Recursion:

1 class Solution {
2 public:
3     int getSum(int a, int b) {
4         
5         return b ? getSum (a ^ b, (a & b) << 1) : a;
6     }
7 };

以上是关于LeetCode 371 Sum of Two Integers的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 第 371 题 (Sum of Two Integers)

Leetcode - 371. Sum of Two Integers

leetcode-371-Sum of Two Integers

LeetCode 371. Sum of Two Integers

Leetcode 371. Sum of Two Integers JAVA语言

Leetcode:371.Sum Of Two Integer