标签:溢出 mod code bsp 1.4 IV span eve for
question:
Modify ThreeSum to work properly even when the int values are so large that adding two of them might cause overflow.
answer:
import edu.princeton.cs.algs4.*; public class ThreeSum { public static int count(int[] a) { 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((long)a[i] + a[j] + a[k] == 0)//只要判断时不溢出就行 cnt++; } } } return cnt; } public static void main(String[] args) { int[] a = In.readInts(args[0]); StdOut.println(count(a)); } }
标签:溢出 mod code bsp 1.4 IV span eve for
原文地址:https://www.cnblogs.com/w-j-c/p/9094440.html