zoukankan      html  css  js  c++  java
  • 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;
        }
    };
    
  • 相关阅读:
    左边菜单导航
    css3实现轮播
    js-统计选项个数
    空间评论。回复。点赞功能
    简单的购物车功能
    字符串常用的几种方法
    React,js实现分页的案列
    python2的cgi程序
    开发环境和工具
    github入门
  • 原文地址:https://www.cnblogs.com/avota/p/5638590.html
Copyright © 2011-2022 走看看