码迷,mamicode.com
首页 > 其他好文 > 详细

1. A + B Problem【easy】

时间:2018-02-03 17:48:16      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:get   rom   you   write   should   sum   func   class   function   

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

Challenge 

Of course you can just return a + b to get accepted. But Can you challenge not do it like that?

 

解法一:

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

 

 

1. A + B Problem【easy】

标签:get   rom   you   write   should   sum   func   class   function   

原文地址:https://www.cnblogs.com/abc-begin/p/8409893.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!