我是靠谱客的博主 成就星星,这篇文章主要介绍不用+号实现两个数之和,现在分享给大家,希望可以做个参考。

转自出处


复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package Hard; /** * Write a function that adds two numbers. You should not use + or any arithmetic operators. 译文: 写一个Add函数求两个数的和,不能使用+号或其它算术运算符。 * */ public class S18_1 { public static int add(int a, int b) { if (b == 0) return a; int sum = a ^ b; // add without carrying int carry = (a & b) << 1; // carry, but don’t add return add(sum, carry); // recurse } public static int randomInt(int n) { return (int) (Math.random() * n); } public static void main(String[] args) { for (int i = 0; i < 100; i++) { int a = randomInt(10); int b = randomInt(10); int sum = add(a, b); System.out.println(a + " + " + b + " = " + sum); } } }


最后

以上就是成就星星最近收集整理的关于不用+号实现两个数之和的全部内容,更多相关不用+号实现两个数之和内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(67)

评论列表共有 0 条评论

立即
投稿
返回
顶部