用 Rust 刷 leetcode 第七题

Problem

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

Example

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.

Solution

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 协议》,转载必须注明作者和本文链接
令狐一冲
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!