欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

Leetcode:371.Sum Of Two Integer

发布时间:2025/3/21 编程问答 33 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Leetcode:371.Sum Of Two Integer 小编觉得挺不错的,现在分享给大家,帮大家做个参考.
题目:
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和b进行循环,直到进位为0为止。计算过程与二进制加法器一致。
  1 public class Solution { 2 public int getSum(int a, int b) { 3 while(b!=0){ 4 int carry = a & b; //计算进位 5 a = a ^ b; //计算和数 6 b = carry<<1; 7 } 8 return a; 9 } 10 }

 

 

转载于:https://www.cnblogs.com/tmx22484/p/6349327.html

总结

以上是生活随笔为你收集整理的Leetcode:371.Sum Of Two Integer的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。