zoukankan      html  css  js  c++  java
  • A plus B Problem

    Source

    Write a function that add two numbers A and B.
    You should not use + or any arithmetic operators.
    
    Example
    Given a=1 and b=2 return 3
    
    Note
    There is no need to read data from standard input stream.
    Both parameters are given in function aplusb,
    you job is to calculate the sum and return it.
    Challenge
    Of course you can just return a + b to get accepted.
    But Can you challenge not do it like that?
    Clarification
    Are a and b both 32-bit integers?
    Yes.
    Can I use bit operation?
    
    Sure you can.

    题解

    不用加减法实现加法,类似数字电路中的全加器,异或求得部分和,相与求得进位,最后将进位作为加法器的输入,典型的递归实现思路。

    Java

    class Solution {
        /*
         * param a: The first integer
         * param b: The second integer
         * return: The sum of a and b
         */
        public int aplusb(int a, int b) {
            int result = a ^ b;
            int carry = a & b;
            carry <<= 1;
            if (carry != 0) {
                result = aplusb(result, carry);
            }
    
            return result;
        }
    }

    源码分析

    递归步为进位是否为0,为0时返回。

    1、异或运算(^),本质上类似相加,0^1=1,0^0=0,1^0=1,1^1=0(这个比较特殊,要看是否要进一位)

    2、与运算(&),对于第一步的结果,1^1都是0,这里就是找出有多少1^1=0的情况,与运算1&1=1

    3、对与运算进行左移,判断是否要进位,如果结果不等于0,则需要进位,下一步就拿异或的结果跟左移的结果相加,递归即可;等于0则不需要,异或的结果就是两个数相加的结果

    复杂度分析

    取决于进位,近似为 O(1). 使用了部分额外变量,空间复杂度为 O(1).

  • 相关阅读:
    FDTD之嵌套扫描
    FDTD之参数扫描与优化
    FDTD之mesh refinement option
    慢光相关知识
    常用单位和公式
    光学知识
    vivo提前批前端笔试题目——辛运员工抽奖
    新版vscode(v1.57)必备配置项——文件标签栏换行展示;Edge集成调试
    无线网络技术实验七——隐藏节点和暴露节点仿真实验
    无线网络技术实验十——卫星网络系统仿真实验
  • 原文地址:https://www.cnblogs.com/lyc94620/p/14855601.html
Copyright © 2011-2022 走看看