zoukankan      html  css  js  c++  java
  • 剑指offer | 不用加减乘除做加法 | 20


    思路分析

    a ^ b  // 不进位加法
    (a & b)<<1 // 进位
    
    本质上这样计算就可以,但是在计算机中要不断的循环
    好好理解
    
    循环几次呢? 最多32次,因为整数在计算机中存储就是32位
    

    注意: 有关于位运算的题目,使用Python都不太方便!

    cpp

    class Solution {
    public:
        int add(int a, int b) {
            while(b){
                int c=(unsigned int)(a&b)<<1; // cpp不运行负数进行<<操作
                a ^= b;
                b = c;
            }
            return a;
        }
    };
    
  • 相关阅读:
    bzoj1009
    bzoj1576 3694
    bzoj3143
    bzoj1391
    bzoj2729
    bzoj2653
    bzoj3261
    bzoj2326
    人件
    优秀的产品
  • 原文地址:https://www.cnblogs.com/Rowry/p/14308721.html
Copyright © 2011-2022 走看看