关于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;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38210187/article/details/80244619