-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBalanceOf.java
More file actions
98 lines (71 loc) · 1.99 KB
/
BalanceOf.java
File metadata and controls
98 lines (71 loc) · 1.99 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package com.algorithm.cjm;
import java.util.ArrayList;
import java.util.List;
/**
* 求一组数值的和
*/
public class BalanceOf {
public static void main(String[] args) {
testMax();
testMin();
}
/**
* 测试最大值溢出
*/
private static void testMax(){
List<Long> trans = new ArrayList<>();
Long tran1 = Long.MAX_VALUE/2;
Long tran2 = Long.MAX_VALUE/3;
Long tran3 = Long.MAX_VALUE/3;
trans.add(tran1);
trans.add(tran2);
trans.add(tran3);
Long amount = balanceOf(trans);
System.out.println(amount);
}
/**
* 测试最小值溢出
*/
private static void testMin(){
List<Long> trans = new ArrayList<>();
Long tran1 = Long.MIN_VALUE/2;
Long tran2 = Long.MIN_VALUE/3;
Long tran3 = Long.MIN_VALUE/3;
trans.add(tran1);
trans.add(tran2);
trans.add(tran3);
Long amount = balanceOf(trans);
System.out.println(amount);
}
/**
* 求一组交易值余额,数值溢出则输出为0
* @param trans 交易值,数组中值可能为正也可能为负数
* @return
*/
private static long balanceOf(List<Long> trans){
long totalAmount = 0l;
if(trans == null || trans.size() == 0){
return totalAmount;
}
for(Long tran : trans){
if(tran == null){
continue;
}
if(tran >= 0){
//临界值最大金额值
long tempMaxAmount = Long.MAX_VALUE - tran;
if(totalAmount > tempMaxAmount){
return 0l;
}
}else {
//临界值最小金额
long tempMinAmount = Long.MIN_VALUE - tran;
if(totalAmount < tempMinAmount){
return 0l;
}
}
totalAmount += tran;
}
return totalAmount;
}
}