The Internet checksum protects IP, TCP, and UDP data against accidental corruption. It uses 16-bit one's-complement arithmetic, where overflow from the top of the word wraps around and is added at the bottom.
Design an InternetChecksumCalculator class:
InternetChecksumCalculator() creates a stateless calculator.int checksum(int[] words) returns the Internet checksum of the supplied 16-bit words.
Compute the checksum in three steps:
- Add every word to a running sum that is wider than 16 bits.
- While the sum exceeds
0xFFFF, fold the carry with (sum & 0xFFFF) + (sum >> 16). - Return the one's complement of the folded sum, masked to 16 bits.
Each call is independent.
Example 1:
Input:
Output:
Explanation: The words are 0x4500, 0x003C, and 0x1C46. They sum to 0x617E, whose 16-bit one's complement is 0x9E81, or 40573.
Example 2:
Input:
Output:
Explanation: The raw sum is 0x10000. Folding its carry produces 0x0001, and complementing that value produces 0xFFFE.
Constraints
1 <= words.length <= 10^50 <= words[i] <= 65535- Every value in
words is an integer. - At most
100 calls are made to checksum.