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.

    Analysis:

    Use bit manipulation.

    Solution 1:

    Caluclate every bit.

     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         int res = 0;
     9         int carry = 0;
    10         for (int i=0;i<32;i++){
    11             int a1 = a & 1;
    12             int b1 = b & 1;
    13             int val = 0;
    14             if (a1==1 && b1==1 && carry==1){
    15                 val = 1;
    16                 carry = 1;
    17             } else if ( (a1==1 && b1==1) || (a1==1 && carry==1) || (b1==1 && carry==1) ) {
    18                 val = 0;
    19                 carry = 1;
    20             } else if (a1==1 || b1==1 || carry==1) {
    21                 val = 1;
    22                 carry = 0;
    23             } else {
    24                 val = 0;
    25                 carry = 0;
    26             }
    27             val = val << i;
    28             res = res | val;
    29             a = a >> 1;
    30             b = b >> 1;
    31         }
    32 
    33         return res;
    34         
    35     }
    36 };

    Solution 2:

    For a + b in any base, we can treat the plus as two part: 1. a + b without carry; 2. the carry generated by a +b. The a+b then equals to part 1 plus part 2. If part1+part2 generates more carry, we can then repeat this procedure, until there is no carry.

     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; //their carry (actuall, need to move to right by one bit.
    10             a = a^b;           //their plus result without carry.
    11             b = carry << 1;
    12         }
    13         return a;
    14     }
    15 };
  • 相关阅读:
    MySQL 中随机抽样:order by rand limit 的替代方案
    mysql下distinct和group by区别对比
    MVC中实现多按钮提交(转)
    js的逻辑 OR 运算符- ||
    js 实现键盘记录 兼容FireFox和IE
    jquery扩展
    sp_executesql的用法
    MVC中,视图的Layout使用
    MVC4的过滤器
    MVC中的Repository模式
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4194937.html
Copyright © 2011-2022 走看看