Created
February 4, 2022 11:20
-
-
Save eNipu/6e8c3917865a4eb1e8cb34184d954d28 to your computer and use it in GitHub Desktop.
overage without overflow
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| fn average_without_overflow(a: i32, b: i32) -> i32 { | |
| return (a & b) + ((a ^ b) >> 1); | |
| } | |
| fn average_with_overflow(a: i32, b: i32) -> i32 { | |
| let avg = (a+b)/2; | |
| return avg; | |
| } | |
| fn main() { | |
| let a = std::i32::MAX; | |
| let b = 1i32; | |
| println!("a={}, b={}", a, b); | |
| let c = average_without_overflow(a, b); | |
| println!("Average without overflow: {}", c); | |
| /* Output | |
| a=2147483647, b=1 | |
| Average without overflow: 1073741824 | |
| */ | |
| let c = average_with_overflow(a, b); | |
| println!("Average with overflow: {}", c); | |
| /* | |
| thread 'main' panicked at 'attempt to add with overflow', src/main.rs | |
| note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace | |
| */ | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment