1. 程式人生 > >關於C語言中輸入一個三位整數,逆序輸出一個三位數

關於C語言中輸入一個三位整數,逆序輸出一個三位數

剛開始在leetcode上刷題,遇到的兩道題目比較簡單,一道是求用一個函式求輸入的兩個數的值,這個簡單就略過了,下面講講一道常見的題目,這是一點小心得,下面附上題目及解題思路:

題目:

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: [−231

,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

解題思路:首先我想到它要是一個負整數的話,我該不該考慮它的符號,其次該不該判斷一下它是不是符合三位數的條件,然後接下來就是逐位求出來了,在程式碼上面寫有註釋怎麼求,下面附上原始碼:

class Solution {
    public int reverse(int x) {
        int a,b,c,y;
        a=x/100;//求百位
        b=(x/10)%10;//求十位
        c=x%10;//求個位
        y=c*100+b*10+a;
        return y;
    }
}