Skip to content

Commit e4e2057

Browse files
committed
add SumOfTwoInt
1 parent 711f1a0 commit e4e2057

File tree

3 files changed

+45
-2
lines changed

3 files changed

+45
-2
lines changed

imooc_fengsehng/InputStringToInt.java renamed to imooc_fengsehng/_01_InputStringToInt.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
*/
88
import java.util.Scanner;
99

10-
public class InputStringToInt
10+
public class _01_InputStringToInt
1111
{
1212
public static void main(String[] args)
1313
{

imooc_fengsehng/CountingBits.java renamed to imooc_fengsehng/_02_CountingBits.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
* 来源:慕课网
77
* 本文原创发布于慕课网 ,转载请注明出处,谢谢合作!
88
*/
9-
public class CountingBits {
9+
public class _02_CountingBits {
1010
public static void main(String[] args) {
1111
int num = 7;
1212
System.out.println("num:" + num);

imooc_fengsehng/_03_SumOfTwoInt.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
3+
* 作者: fengsehng
4+
* 链接:http://www.imooc.com/article/11317
5+
* 来源:慕课网
6+
* 本文原创发布于慕课网 ,转载请注明出处,谢谢合作!
7+
*/
8+
public class _03_SumOfTwoInt {
9+
public static void main(String[] args) {
10+
int a = 3, b = 10;
11+
int sum1 = getSum1(a, b);
12+
int sum2 = getSum2(a, b);
13+
System.out.println("two integer:" + a + ", " + b);
14+
System.out.println("sum1:" + sum1);
15+
System.out.println("sum2:" + sum2);
16+
}
17+
// 异或又被称其为“模2加法“
18+
// 设置变量recipe模拟进位数字,模拟加法的实现过程
19+
public static int getSum1(int a, int b){
20+
int r = 0, c = 0, recipe = 1;
21+
while ((a | b | c) != 0) {
22+
if (((a ^ b ^ c) & 1) != 0)
23+
r += recipe;
24+
recipe <<= 1;
25+
c = (a & b | b & c | a & c) & 1;
26+
a >>>= 1;
27+
b >>>= 1;
28+
}
29+
return r;
30+
}
31+
32+
// a ^ b,求得结果
33+
// a & b,求得进位
34+
// 相加
35+
public static int getSum2(int a, int b){
36+
while (b != 0){
37+
int c = a & b; //carry
38+
a ^= b; //add
39+
b = c << 1;
40+
}
41+
return a;
42+
}
43+
}

0 commit comments

Comments
 (0)