【题目描述】
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位 整数么?
- 是的
我可以使用位运算符么?
- 当然可以
【本题答案】
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)); } }
本文介绍了一种不使用传统的加法运算符来计算两个32位整数之和的方法。通过位操作实现加法逻辑,递归地处理进位问题,直至没有进位发生。这种方式巧妙地绕过了直接的数学运算,展示了位操作的强大功能。
386

被折叠的 条评论
为什么被折叠?



