zoukankan      html  css  js  c++  java
  • 剑指offer--12.不用加减乘除做加法

     位运算,好久没用了

    &:都为1,结果为1

    ^:相同为0,不同为1

    |:有1,结果为1

    <<:左移

    ------------------------------------------------------------------------------

    时间限制:1秒 空间限制:32768K 热度指数:97386

    题目描述

    写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。
    思路:
    1.用位运算计算各个位上相加的结果
    2.考虑各个位上进位的情况
    3.将1结果与2结果相加
    eg:
    111+899
    首先‭01101111‬+‭001110000011‬得‭001111101100‬:1004

    1004

    进行&运算得到‭0011‬,左移进位:110
    6

    110异或001111101100‬得到‭001111101010‬:1002
    1002

    进行&运算得到‭100,左移进位得:1000
    8

    异或得到:‭001111100010‬
    994

    进行&运算得到‭100,左移进位得:10000
    16

    异或得到:‭‭001111110010‬
    1010

    进行&运算得到‭100,左移进位得:0

    计算完毕!

    过程类似:111+899,1+9进1,1+9进1,进到1+8+1再进1,得到1010.当没有进位时,计算完毕。

    class Solution {
    public:
        int Add(int num1, int num2)
        {
            while(num2 != 0) {
                int tmp = num1 ^ num2;
                num2 =  (num1&num2) << 1;
                num1 = tmp;
            }
            return num1;
        }
    };
  • 相关阅读:
    73. Set Matrix Zeroes
    289. Game of Live
    212. Word Search II
    79. Word Search
    142. Linked List Cycle II
    141. Linked List Cycle
    287. Find the Duplicate Number
    260. Single Number III
    137. Single Number II
    Oracle EBS中有关Form的触发器的执行顺序
  • 原文地址:https://www.cnblogs.com/slothrbk/p/10565500.html
Copyright © 2011-2022 走看看