返回介绍

solution / 2200-2299 / 2235.Add Two Integers / README_EN

发布于 2024-06-17 01:03:08 字数 3653 浏览 0 评论 0 收藏 0

2235. Add Two Integers

中文文档

Description

Given two integers num1 and num2, return _the sum of the two integers_.

 

Example 1:

Input: num1 = 12, num2 = 5
Output: 17
Explanation: num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned.

Example 2:

Input: num1 = -10, num2 = 4
Output: -6
Explanation: num1 + num2 = -6, so -6 is returned.

 

Constraints:

  • -100 <= num1, num2 <= 100

Solutions

Solution 1

class Solution:
  def sum(self, num1: int, num2: int) -> int:
    return num1 + num2
class Solution {
  public int sum(int num1, int num2) {
    return num1 + num2;
  }
}
class Solution {
public:
  int sum(int num1, int num2) {
    return num1 + num2;
  }
};
func sum(num1 int, num2 int) int {
  return num1 + num2
}
function sum(num1: number, num2: number): number {
  return num1 + num2;
}
impl Solution {
  pub fn sum(num1: i32, num2: i32) -> i32 {
    num1 + num2
  }
}
int sum(int num1, int num2) {
  return num1 + num2;
}

Solution 2

class Solution:
  def sum(self, num1: int, num2: int) -> int:
    num1, num2 = num1 & 0xFFFFFFFF, num2 & 0xFFFFFFFF
    while num2:
      carry = ((num1 & num2) << 1) & 0xFFFFFFFF
      num1, num2 = num1 ^ num2, carry
    return num1 if num1 < 0x80000000 else ~(num1 ^ 0xFFFFFFFF)
class Solution {
  public int sum(int num1, int num2) {
    while (num2 != 0) {
      int carry = (num1 & num2) << 1;
      num1 ^= num2;
      num2 = carry;
    }
    return num1;
  }
}
class Solution {
public:
  int sum(int num1, int num2) {
    while (num2) {
      unsigned int carry = (unsigned int) (num1 & num2) << 1;
      num1 ^= num2;
      num2 = carry;
    }
    return num1;
  }
};
func sum(num1 int, num2 int) int {
  for num2 != 0 {
    carry := (num1 & num2) << 1
    num1 ^= num2
    num2 = carry
  }
  return num1
}
function sum(num1: number, num2: number): number {
  while (num2) {
    const carry = (num1 & num2) << 1;
    num1 ^= num2;
    num2 = carry;
  }
  return num1;
}
impl Solution {
  pub fn sum(num1: i32, num2: i32) -> i32 {
    let mut num1 = num1;
    let mut num2 = num2;
    while num2 != 0 {
      let carry = (num1 & num2) << 1;
      num1 ^= num2;
      num2 = carry;
    }
    num1
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文