Created
December 23, 2014 23:30
-
-
Save FreeFull/d915153967474bb9aab0 to your computer and use it in GitHub Desktop.
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 naive_int_abs_diff(x: int, y: int) -> uint { | |
| use std::num::SignedInt; | |
| (x - y).abs() as uint | |
| } | |
| fn naive_uint_abs_diff(x: uint, y: uint) -> uint { | |
| naive_int_abs_diff(x as int, y as int) | |
| } | |
| fn uint_abs_diff(x: uint, y: uint) -> uint { | |
| if x > y { | |
| x - y | |
| } else { | |
| y - x | |
| } | |
| } | |
| fn int_abs_diff(x: int, y: int) -> uint { | |
| use std::int::MIN; | |
| let x = (x - MIN) as uint; | |
| let y = (y - MIN) as uint; | |
| uint_abs_diff(x, y) | |
| } | |
| fn main() { | |
| use std::{int, uint}; | |
| let (x, y) = (int::MIN, int::MAX); | |
| // The naive subtraction results in the value 1, while the correct result is uint::MAX | |
| println!("naive int abs diff: {}, correct int abs diff: {}", naive_int_abs_diff(x, y), int_abs_diff(x, y)); | |
| // Exact same problem, except with unsigned integer inputs. | |
| let (x, y) = (0, uint::MAX); | |
| println!("naive uint abs diff: {}, correct uint abs diff: {}", naive_uint_abs_diff(x, y), uint_abs_diff(x, y)); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment