142.Sum of Two Integers

来源:互联网 发布:社交软件 编辑:程序博客网 时间:2024/06/03 20:17

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.

Credits:
Special thanks to @fujiaozhu for adding this problem and creating all test cases.

Subscribe to see which companies asked this question


/** * 写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。 * 采用位运算来满足这个不用加减乘除的条件。 * Step1:先让两个数字相加,但是不做进位相当于做位异或的操作,00 = 0,11=0,01=1,10=1; * Step2:计算产生的进位,让两个数字位与操作,然后向左移动一位;备注,位与操作只有两个数都是1的时候才是1,其他结果都是0 * Step3:前两步的结果相加,重复前两个步骤直到进位为0. */public int getSum(int num1,int num2) {int sum;int carry;//产生的进位sum = num1^num2;carry = (num1&num2)<<1;while(carry != 0){num1 = sum;num2 = carry;sum = num1^num2;carry = (num1&num2)<<1;}return sum;    }


0 0
原创粉丝点击