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;
        }
    };
    
  • 相关阅读:
    iOS设备后台播放音乐方法
    iOS 编译64位FFMPEG
    os8 location authorization 错误.
    IOS 使用新浪微博SDK
    IOS 解析歌词lrc
    IOS 通过button获取cell
    IOS 解析XML文档
    OC .(点)与->(箭头)用法区别
    黑苹果安装合集
    Hello,World
  • 原文地址:https://www.cnblogs.com/avota/p/5638590.html
Copyright © 2011-2022 走看看