两个整数求平均值,防止溢出的问题
http://bylijinnan.iteye.com/blog/1463337
bigInteger 没有上限,取决于计算机的内存;
https://www.jianshu.com/p/8b89ab19db84
其实也可以这样:
package com.stono; public class Test02 { public static void main(String[] args) { int i1 = Integer.MAX_VALUE-2; // 214748 3645 int i2 = Integer.MAX_VALUE-3; // 214748 3644 System.out.println((i1+i2)/2); // 直接相加就溢出了 int sa = sumAverage(i1,i2); System.out.println(sa); System.out.println(1/2); // 这个等于0的; System.out.println(sumAverage(7, 7)); System.out.println(7/2); } private static int sumAverage(int i1, int i2) { int i1sa = i1/2; int i2sa = i2/2; int sasa = (i1%2+i2%2)/2; // 防止两个奇数的末位被抹掉了; return i1sa+i2sa+sasa; } }
用位操作提升一下速度:
private static int sumAverage(int i1, int i2) { int i1sa = i1>>1; int i2sa = i2>>1; int sasa = (i1&1+i2&1)>>1; // 防止两个奇数的末位被抹掉了; return i1sa+i2sa+sasa; }