leecode 解题总结:363. Max Sum of Rectangle No Larger Than K

本文介绍了一种不使用加减运算符实现两个整数相加的方法。通过位运算技巧,如异或和按位与,逐步计算出不考虑进位的和及进位值,并重复此过程直至无进位。
#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
using namespace std;
/*
问题:
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.

分析:不允许使用加减号来求两个数的和。设置一个类,里面
存放一个静态计数器,实例化之后,每次调用一次,累加计数器。
或者位操作,求出两数相加的时候,先不进位的值val1,和单独求出进位的部分val2
然后进行val1与val2进行加操作。

举例
3 5
3: 0011
5: 0101
单独累加不进位,就是异或运算得到3^5=0110=6
单独进位运算,两个都是1才进位:0010=2(如果两个数字第i位都是1,进位为1 << (i+1),要向左多移动一维)
6+2,不对。

0110
0010
再次求carry和以后结果

还是位操作,做一些判断而已
进位只有:bit1,bit2,carry中至少两个为1

输入:
1 2
1 -2
1 -1
输出:
3
-1
0

关键:
1 	记住,不允许使用符号计算结果,采用位运算。注意:carry = a & b , a = a ^ b,b = carry << 1
把a视作单独计算不进位的结果,把b视作单独进位不计算的结果,直到进位b为0,即可
*/


class Solution {
public:
	int count(int bit1 , int bit2 , int carry)
	{
		int num = 0;
		if(0 != bit1)
		{
			num++;
		}
		if(0 != bit2)
		{
			num++;
		}
		if(1 == carry)
		{
			num++;
		}
		return num;
	}

    int getSum2(int a, int b) {
		int result = 0;
		int carry = 0;
		//两个数不断向右移动即可
		int i = 0;
		int mask;
		for( i = 0 ; i < 32 ; i++)
		{
			mask = (1 << i);
			int bit1 = mask & a;
			int bit2 = mask & b;
			int count1 = count(bit1 , bit2 ,carry);
			int curBit = count1 % 2;
			carry = count1 / 2;
			result |= (curBit << i);
		}
		return result;
    }

	//注意:carry = a & b , a = a ^ b,b = carry << 1
	//把a视作单独计算不进位的结果,把b视作单独进位不计算的结果,直到进位b为0,即可
    int getSum(int a, int b) {
		int carry = 0;
		while(b != 0)
		{
			carry = a & b;//求单独进位
			a = a ^ b;//求单独计算结果
			b = carry << 1;//进位左移一位
		}
		return a;
	}
};


void process()
{
	 int a;
	 int b;
	 Solution solution;
	 int result;
	 while(cin >> a >> b )
	 {
		 result = solution.getSum(a , b);
		 cout << result << endl;
	 }
}

int main(int argc , char* argv[])
{
	process();
	getchar();
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值