「每日一道演算法題」Reverse Integer

weixin_33850890發表於2019-01-03

Algorithm

OJ address

Leetcode website : 7. Reverse Integer

Description

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.

Solution in C (one)

int reverse(int x) {
    int t = 0;
    if (x == 0) return 0;
    while (!x%10) {
        x/=10;
    }
    int sum = 0;
    long long reallysum = 0;
    while (x) {
        reallysum *=10;
        sum *= 10;
        t = x%10;
        reallysum+=t;
        sum+=t;
        x/=10;
    }
    if (reallysum != sum) return 0;
    return sum;
}

Solution in C (Two)

int reverse(int x) {
    int t = 0;
    if (x == 0) return 0;
    while (!x%10) {
        x/=10;
    }
    int sum = 0;
    int tmp = 0;
    while (x) {
        sum *= 10;
        if (sum/10 != tmp) return 0;
        t = x%10;
        sum+=t;
        x/=10;
        tmp = sum;
    }
    return sum;
}

My Idea

題目含義是,給定一個int型別的整數,然後進行數字反轉,輸出。

  1. 反轉後,將前導0去掉,例如2300 -> 0023 ->23
  2. 如果超過 INT_MAX , 或者小魚 INT_MIN,則輸出0,關於這個如何判斷,有兩種簡單的方法,第一種方法是用long long來存取變數,如果大於INT_MAX或者小於INT_MIN,則輸出0.第二種方法就是如果超出最大值,或小於最小值,則你最高位後面的尾數是會因為超出最大值而跟著改變的,所以你只要檢測尾數如果變化,就輸出0即可,這就是我程式碼裡的第二種方法。

相關文章