用 Rust 刷 leetcode 第七題

linghuyichong發表於2020-01-13

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:
Input: 123
Output: 321

Example 2:
Input: -123
Output: -321

Example 3:
Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31^,  2^31 ^− 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

impl Solution {
    pub fn reverse(x: i32) -> i32 {
        let mut flag: bool = true;
        let mut data: i32 = x;
        let mut result: i64 = 0;
        let th: u32 = (1<<31);
        let th1: i32 = (th-1) as i32;
        //println!("th = {}", th);
        //println!("th1 = {}", th1);

        if data < 0 {
            flag = false;
            data = -data;
        }

        while data > 0 {
            result = result*10 + ((data%10) as i64);
            data = data/10;
            //println!("result = {}, data = {}", result, data);

            if result > (th1 as i64){
                return 0;
            }
        }

        //println!("result = {}", result);
        let mut result = result as i32;
        if flag == false {
            result = -result;
            let th2 = th as i32;
            if result < th2 {
                return 0;
            }
        } else if result > th1 {
            return 0;
        }

        result
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結
令狐一衝

相關文章