Back to course home
0% completed
Vote For New Content
Solution will fail in leetcode with Java due to Integer overflow
Giang Pham
Jul 10, 2024
count += remainderFrequency[0] * (remainderFrequency[0] - 1) / 2;
- Java arithmetic operators are executed left to right
- Fail test case in leetcode: an array length of 60000 containing only 60.
- Array: [60 60 60 60 60 60 60 ....] (60000 60s are in this input array)
- remainderFrequency[0] * remainderFrequency[0] - 1 = 60000 * 59999 = 3599940000
- 3599940000 is larger than the largest integer value in Java causing overflow
- Solution: casting one of the number to long to preserve precision and prevent integer overflow
count += (long)remainderFrequency[0] * (remainderFrequency[0] - 1) / 2;
0
0
Comments
Comments
On this page