# 算法练习(55): 整形溢出问题处理(1.4.2)

• 整形溢出问题处理
• In库的熟练使用

### 题目

1.4.2 修改TreeSum,正确处理两个较大的int值相加可能溢出的情况

1.4.2 Modify ThreeSum to work properly even when the int values are so large that adding two of them might cause overflow.

### 分析

ThreeSum的代码如下

``````public class ThreeSum {
public static int count(int[] a) { // Count triples that sum to 0.
int N = a.length;
int cnt = 0;
for (int i = 0; i < N; i++)
for (int j = i + 1; j < N; j++)
for (int k = j + 1; k < N; k++)
if (a[i] + a[j] + a[k] == 0)
cnt++;
return cnt;
}

public static void main(String[] args) {
StdOut.println(count(a));
}
}
``````

1Kints.txt2Kints.txt4Kints.txt8Kints.txt16Kints.txt32Kints.txt1Minints.txt放在当前项目下了，我们可以通过方法:

``````String filePathString = System.getProperty("user.dir");
String intFileString = filePathString + "/src/com/kyson/chapter1/section4/" + "1Kints.txt";
``````

### 答案

``````public class ThreeSum2 {
public static int count(long[] a) { // Count triples that sum to 0.
int N = a.length;
int cnt = 0;
for (int i = 0; i < N; i++)
for (int j = i + 1; j < N; j++)
for (int k = j + 1; k < N; k++)
if (a[i] + a[j] + a[k] == 0)
cnt++;
return cnt;
}

public static void main(String[] args) {
String filePathString = System.getProperty("user.dir");
String intFileString = filePathString
+ "/src/com/kyson/chapter1/section4/" + "5ints.txt";
In in = new In(intFileString);
StdOut.println(count(a));
}
}
``````

ThreeSum2.java