lintcode-1. A + B Problem

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/richenyunqi/article/details/80686715

欢迎访问我的lintcode题解目录https://blog.csdn.net/richenyunqi/article/details/81149577

 

算法设计:

这是一道考察位运算的题目。如何利用位运算求解两数之和呢?

在不考虑进位的情况下两数之和可以用异或运算^来表示,例如0+1的和就可以通过0^1=1得到;进位可以利用与运算&再左移一位来表示,例如1+1可以用1&1=1,1左移一位1位=10,十进制即为2得到。

下面以7+1=8,二进制表示为111+001=1000为例:

 

  1. 在不考虑进位的情况下111^001=110;进位为111&001=001,将进位左移一位变为010
  2. 在不考虑进位的情况下110^010=100;进位为110&010=010,将进位左移一位变为100
  3. 在不考虑进位的情况下100^100=000;进位为100&100=100,将进位左移一位变为1000
  4. 在不考虑进位的情况下0000^1000=1000;进位为0000&1000=0000,进位为0,算法结束。此时得到了两数之和1000

非递归的C++代码:

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

递归C++代码:

class Solution {
public:
    /**
     * @param a: An integer
     * @param b: An integer
     * @return: The sum of a and b 
     */
    int aplusb(int a, int b) {
        return b==0?a:aplusb(a^b,(a&b)<<1);
    }
};

这里怎么解决?A + B Problem II

02-04

做了杭电ACM1002的题目,有点问题```rn先看题目:rnrn=======================================================================================rnProblem DescriptionrnI have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.rnrnInputrnThe first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line consists of two positive integers, A and B. Notice that the integers are very large, that means you should not process them by using 32-bit integer. You may assume the length of each integer will not exceed 1000.rnrnOutputrnFor each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line is the an equation "A + B = Sum", Sum means the result of A + B. Note there are some spaces int the equation. Output a blank line between two test cases.rnrnrnSample Inputrn2rn1 2rn112233445566778899 998877665544332211rn rnSample OutputrnCase 1:rn1 + 2 = 3rnrnCase 2:rn112233445566778899 + 998877665544332211 = 1111111111111111110rnrn===========================================================================================rnrn我做的代码rn[code=C/C++]rn#includern#include rnusing namespace std;rnconst int Len=102;rnint a[Len],b[Len];rnrnvoid main()rnrn char st1[102],st2[102];rn int i,j,n,k,l1,l2;rn cin>>n;rn if((1<=n)&&(n<=20))rn rn for(k=0;k>st1>>st2; rn l1=strlen(st1);rn l2=strlen(st2); rn for (i=0;i=1;i--) //数位匹配rn rn a[i-1]=a[i-1]+a[i]/10;rn a[i]=a[i]%10;rn rn i=0;rn while (a[i]==0 && i+1

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试