dkim   5년 전

아래의 입력에 대해, 절대값이 작은 -2147483647이 -2147483648보다 먼저 출력되어야 합니다. 그런데, 정답 처리된 코드 중 여럿이 그렇지 않습니다. 현재 입력 조건은 "입력되는 정수는 -231보다 크거나 같고, 231보다 작다"이므로, -2147483648(= -231)은 정당한 입력값입니다. 그런데, -231의 절대값은 231-1보다 크기 때문에, 근래의 거의 모든 플랫폼 상에서 부호있는 32비트 정수형(int)으로 표현할 수 없습니다. 그 결과, 단항 연산자 - (negation), 표준 C 라이브러리 int abs(int)  함수와 자바 int Math.abs(int) 함수 등이 그 값에 대해 기대한 대로 동작하지 않습니다:

https://en.cppreference.com/w/c/language/operator_arithmetic#Overflows

When signed integer arithmetic operation overflows (the result does not fit in the result type), the behavior is undefined:

https://en.cppreference.com/w/c/numeric/math/abs

The behavior is undefined if the result cannot be represented by the return type.

https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#abs-int-

Note that if the argument is equal to the value of Integer.MIN_VALUE, the most negative representable int value, the result is that same value, which is negative.

따라서, 데이터를 추가하여 부호있는 정수형의 양수와 음수의 표현 가능 범위가 대칭적이지 않다는 점을 되새길 기회로 삼거나, 입력 조건을 "-231보다 크고, 231보다 작다"로 변경할 필요가 있어 보입니다.

startlink   5년 전

수정했습니다.

댓글을 작성하려면 로그인해야 합니다.