首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >【每天一道编程系列-2018.3.11】—— A + B Problem

【每天一道编程系列-2018.3.11】—— A + B Problem

作者头像
yesr
发布于 2019-03-14 12:50:06
发布于 2019-03-14 12:50:06
3480
举报
文章被收录于专栏:leetcode_solutionsleetcode_solutions

【题目描述】

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.

【题目大意】

给出两个整数a和b, 求他们的和, 但不能使用 + 等数学运算符。

 注意事项

你不需要从输入流读入数据,只需要根据aplusb的两个参数a和b,计算他们的和并返回就行。

说明

a和b都是 32位 整数么?

  • 是的

我可以使用位运算符么?

  • 当然可以

【本题答案】

代码语言:javascript
复制
package blog;

/**
 * @author yesr
 * @create 2018-03-11 下午11:28
 * @desc
 **/
public class Test0310 {

        /*
         * @param a: The first integer
         * @param b: The second integer
         * @return: The sum of a and b
         */
        private static int plus(int a, int b) {
            if (b == 0)
                return a;
            else
                return plus(a^b, (a&b) << 1);
        }

    public static void main(String[] args) {
        System.out.println(plus(3,0));
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018年03月11日,如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  •  Notice
  •  注意事项
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档