How to portably find out min(INT_MAX, abs(INT_MIN))?

前端 未结 6 1367
感情败类
感情败类 2020-12-11 00:10

How can I portably find out the smallest of INT_MAX and abs(INT_MIN)? (That\'s the mathematical absolute value of INT_MIN, not a call

6条回答
  •  隐瞒了意图╮
    2020-12-11 00:27

    INT_MAX + INT_MIN < 0 ? INT_MAX : -INT_MIN
    

    Edited to add explanation: Of course the difficulty is that -INT_MIN or abs(INT_MIN) will be undefined if -INT_MIN is too big to fit in an int. So we need some way of checking whether this is the case. The condition INT_MAX + INT_MIN < 0 tests whether -INT_MIN is greater than INT_MAX. If it is, then INT_MAX is the smaller of the two absolute values. If not, then INT_MAX is the larger of the two absolute values, and -INT_MIN is the correct answer.

提交回复
热议问题