不用“+”运算符,实现A+B运算

来源: lintcode A+B问题

解决方法 :位操作

六种按位操作符:

  • 按位与:&
  • 按位或:|
  • 按位取反:~
  • 按位异或:^
  • 按位左移:<< (高位丢弃,低位补零)
  • 按位右移:>> (对无符号数,高位补0,有符号数,各编译器处理方法不一样,有的补符号位(算术右移),有的补0(逻辑右移))

解决加法问题

  • a^b; 得到不含进位之和

  • (a&b)<<1; 进位

  • 只要进位不为零,则迭代;否则返回

// java

public class Solution {
    /*
     * @param : An integer
     * @param : An integer
     * @return: The sum of a and b
     */
    public int aplusb(int a, int b) {

        int sum_without_carry, carry;

        sum_without_carry = a^b; //没有进位的和
        carry = (a&b)<<1; //进位
        if(carry==0)
            return sum_without_carry;
        else 
            return aplusb(sum_without_carry, carry);   
    }
};
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++中的高精度运算符重载是指对整数进行大数运算时,通过重载运算符实现对大数的加减乘除等操作。一般情况下,C++内置的整数类型(如int、long等)有一定的位数限制,无法处理超过其表示范围的大数。而通过运算符重载,我们可以自定义一个类来表示大数,并对其进行各种运算操作。 以下是一个简单的示例,展示了如何实现C++中的高精度运算符重载: ```cpp #include <iostream> #include <vector> using namespace std; class BigInteger { private: vector<int> digits; // 用vector存储大数的每一位 public: BigInteger() {} BigInteger(int num) { while (num > 0) { digits.push_back(num % 10); num /= 10; } } BigInteger operator+(const BigInteger& other) const { BigInteger result; int carry = 0; int i = 0; while (i < digits.size() || i < other.digits.size() || carry != 0) { int sum = carry; if (i < digits.size()) { sum += digits[i]; } if (i < other.digits.size()) { sum += other.digits[i]; } result.digits.push_back(sum % 10); carry = sum / 10; i++; } return result; } friend ostream& operator<<(ostream& os, const BigInteger& num) { for (int i = num.digits.size() - 1; i >= 0; i--) { os << num.digits[i]; } return os; } }; int main() { BigInteger a(123456789); BigInteger b(987654321); BigInteger c = a + b; cout << "a + b = " << c << endl; return 0; } ``` 在上述示例中,我们定义了一个名为BigInteger的类,用于表示大数。通过重载加法运算符`+`,我们可以实现对两个BigInteger对象的相加操作。同时,我们还重载了输出流运算符`<<`,以便能够直接输出BigInteger对象的值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值