zoukankan      html  css  js  c++  java
  • Lintcode: A+B problem

    For given numbers a and b in function aplusb, return the sum of them.
    
    Note
    You don't need to parse the input and output. Just calculate and return.
    
    Example
    If a=1 and b=2 return 3
    
    Challenge
    Can you do it with out + operation?
    
    Clarification
    Are a and b both 32-bit integers?
    
        - Yes.

    直接+没什么好说的,关键在于不用+的操作:

    考验Bit Operation, 可以用按位^异或两个操作数对应位以及carry,只是carry是1还是0需要分情况讨论。求更优的解法

     1 class Solution {
     2     /*
     3      * param a: The first integer
     4      * param b: The second integer
     5      * return: The sum of a and b
     6      */
     7     public int aplusb(int a, int b) {
     8         // Click submit, you will get Accepted!
     9         int i = 0;
    10         int res = 0;
    11         int carry = 0;
    12         for (; i<32; i++) {
    13             int aa = (a >> i) & 1;
    14             int bb = (b >> i) & 1;
    15             res |= (aa ^ bb ^ carry) << i;
    16             if (aa == 1 && bb == 1 || ((aa ==1 || bb == 1) && carry == 1)) {
    17                 carry = 1;
    18             }
    19             else carry = 0;
    20         }
    21         return res;
    22     }
    23 };

     贴一个别人的简洁思路:

    位运算实现整数加法本质就是用二进制进行运算。
    其主要用了两个基本表达式:
    x^y //执行加法,不考虑进位。
    (x&y)<<1 //进位操作
    令x=x^y ;y=(x&y)<<1 进行迭代,每迭代一次进位操作右面就多一位0,最多需要“加数二进制位长度”次迭代就没有进位了,此时x^y的值就是结果。

    我们来做个3位数的加法:
    101+011=1000 //正常加法
    位运算加法:
    (1) 101 ^ 011 = 110
    (101 & 011)<<1 = 010
    (2) 110 ^ 010 = 100
    (110 & 010)<<1 = 100
    (3) 100 ^ 100 = 000
    (100 & 100)<<1 = 1000
    此时进行相加操作就没有进位了,即000 ^ 1000=1000即是最后结果。

     1 class Solution {
     2     /*
     3      * param a: The first integer
     4      * param b: The second integer
     5      * return: The sum of a and b
     6      */
     7     public int aplusb(int a, int b) {
     8         while(b != 0){
     9             int carry = a & b;
    10             a = a ^ b;
    11             b = carry << 1;
    12         }
    13         return a;
    14     }
    15 }

     或者用Recursion写:

    1     public int aplusb(int a, int b) {
    2         // Click submit, you will get Accepted!
    3         if (b == 0) return a;
    4         int sum = a^b;
    5         int carry = (a&b)<<1;
    6         return aplusb(sum, carry);
    7     }
  • 相关阅读:
    (数据科学学习手札09)系统聚类算法Python与R的比较
    写完代码就去吃饺子|The 10th Henan Polytechnic University Programming Contest
    《四月物语》
    PAT(甲级)2017年春季考试
    PAT(甲级)2017年秋季考试
    2019年全国高校计算机能力挑战赛 C语言程序设计决赛
    CF#603 Div2
    redhat7 上安装dummynet
    cassandra 如何写数据以及放置副本
    Eclipse中设置VM参数
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/4269079.html
Copyright © 2011-2022 走看看