371. Sum of Two Integers -- Avota

问题描述:

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

解题思路:

我们知道,机器内部是使用二进制表示数字,其中整数用补码表示。既然不能直接调用系统实现好的十进制“+、-”运算符,那就可以考虑自己实现补码加法,对于使用补码表示的整数有以下性质:[X]补 + [Y]补 = [X+Y]补

示例代码:

class Solution {
public:
    int getSum(int a, int b) {
        int result = 0;
    	int flag = 0, jie = 1;
    	for (int i = 0; i < 32; i++){
    		int lastA = a & 1;
    		int lastB = b & 1;
    		if (flag == 1) {
    			if (lastA == 1 && lastB == 1) {
    				flag = 1;
    				result |= jie;
    			}
    			else if (lastA == 0 && lastB == 0) {
    				flag = 0;
    				result |= jie;
    			}
    			else {
    				flag = 1;
    			}
    		}
    		else {
    			if (lastA == 1 && lastB == 1) {
    				flag = 1;
    			}
    			else if (lastA == 0 && lastB == 0) {
    				flag = 0;
    			}
    			else {
    				flag = 0;
    				result |= jie;
    			}
    		}
    		jie *= 2;
    		a = a >> 1;
    		b = b >> 1;
    	}
    	if (flag) {
    		result |= jie;
    	}
    	return result;
    }
};
posted @ 2016-07-03 19:06  Avota  阅读(165)  评论(0编辑  收藏  举报