[关闭]
@XQF 2018-03-07T23:01:12.000000Z 字数 598 阅读 928

如何不用比较就得出两个数的最大值和最小值?

数据结构与算法



  1. public class Solution {
  2. //可能溢出
  3. public int max(int a, int b) {
  4. return (a + b + Math.abs(a - b)) / 2;
  5. }
  6. public int min(int a, int b) {
  7. return (a + b - Math.abs(a - b)) / 2;
  8. }
  9. //不会溢出
  10. public int max1(int a, int b) {
  11. return (int) ((long) a + (long) b + Math.abs((long) a - (long) b)) / 2;
  12. }
  13. public int min1(int a, int b) {
  14. return (int) ((long) a + (long) b - Math.abs((long) a - (long) b)) / 2;
  15. }
  16. public static void main(String[] args) {
  17. Solution solution = new Solution();
  18. System.out.println(solution.max(3, 5));
  19. System.out.println(solution.min(3, 5));
  20. System.out.println(solution.max1(3, 5));
  21. System.out.println(solution.min1(3, 5));
  22. }
  23. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注