1. A + B问题

Write a function that add two numbers A and B. You should not use + or any arithmetic operators.

 Notice

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.

Clarification

Are a and b both 32-bit integers?

  • Yes.

Can I use bit operation?

  • Sure you can.
Example

Given a=1 and b=2 return 3

编写一个函数,添加两个数字A和B.您不应该使用+或任何算术运算符。


 注意
不需要从标准输入流中读取数据。两个参数都在函数中给出aplusb,您的工作是计算总和并返回它。

澄清
a和b都是32-bit整数吗?
是。
我可以使用位操作吗?
你当然可以。

鉴于a=1与b=2回报3


位操作(是对二进制进行操作)

&     与     同为1,显示为1。

|       或     同为0,显示为0。

^     异或   相同为0,想异为1.。

~     取反    0->1,1->0。

<<   左移    向左进位。

位操作进行加法的算法大概分为两步:

1. 做异或操作,得到不同的位,得到另一个值(不考虑进位,直接得出计算结果)

2. 做与操作,得到相同的位,左移进位得到一个值(进位,用二进制表示)

若两个值中有一个为0,那么结果就是另一个。

int aplusb(int a, int b)
{
int x, y;
x = a;
y = b;
while(x != 0 && y != 0)
{
x = a ^ b;
y = (a & b) << 1;
a = x;
b = y;
}
return x==0?y:x;

}



举例:x = 1,y = 2,结果为3。

x二进制为01,y二进制位10.

1--   x = a^b    x 二进制表示11,为3.

2--   y = (a & b) << 1     a & b = 00    左移1位,y二进制表示000,为0。




2018/1/22

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值