1 · A + B 问题(LintCode,算法,入门)

这篇博客探讨了一种不使用加法运算符计算两个整数a和b之和的方法。虽然直接返回a+b是最简单的方式,但挑战在于寻找其他实现方式。示例中给出了Go、Python3和Rust三种语言的实现,它们都成功地计算了两个整数的和,并且在时间效率和空间占用上表现出色。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

描述

给出两个整数 aa 和 bb , 求他们的和并以整数(int)的形式返回。

你不需要从标准输入流读入数据,只需要根据aplusb传入的两个参数 a 和 b,计算他们的和并返回就行。
-2^{31} \leq a, b \leq 2^{31} - 1

-2^{31} \leq a + b \leq 2^{31} - 1

样例

样例 1:

输入:

a = 1
b = 2

输出:

3

解释:

a + b = 1 + 2 = 3

样例 2:

输入:

a = -1
b = 1

输出:

0

解释:

a + b = -1 + 1 = 0

挑战

显然你可以直接返回 a + b,但是你是否可以挑战不这样做?(不使用+等算数运算符)

Go语言:

/**
 * @param a: An integer
 * @param b: An integer
 * @return: The sum of a and b 
 */
func Aplusb(a int, b int) int {
    // write your code here
    return a+b
}

Accepted        100%

41 ms时间消耗         5.38 MB空间消耗        您的提交打败了88.40 %的提交

Python 3:

class Solution:
    """
    @param a: An integer
    @param b: An integer
    @return: The sum of a and b 
    """
    def aplusb(self, a: int, b: int) -> int:
        # write your code here
        return (a+b)

Accepted        100%

81 ms时间消耗        6.00 MB空间消耗        您的提交打败了98.20 %的提交

Rust:

pub struct Solution;

impl Solution {
    // @param a: An integer
    // @param b: An integer
    // @return: The sum of a and b 
    pub fn aplusb(a: i32, b: i32) -> i32 {
        // write your code here
        return a+b;
    }
}

Accepted        100%

41 ms时间消耗        5.57 MB空间消耗        您的提交打败了100.00 %的提交

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值