LintCode37-反转一个3位整数

1.题目

反转一个只有3位数的整数。

2.思路及代码

1.直接对整数取余

class Solution {
public:
    /**
     * @param number: A 3-digit number.
     * @return: Reversed number.
     */
    int reverseInteger(int number) {
        int x = number;
        int rev = 0;
        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            rev = rev * 10 + pop;
        }
        return rev;
    }
};
class Solution:
    """
    @param number: A 3-digit number.
    @return: Reversed number.
    """
    def reverseInteger(self, number):
        rev = 0 
        while(number!=0):
            pop = number % 10
            number //= 10
            rev = rev * 10 + pop
        return rev

c++中“/”除完直接向下取整,python中“/”得到小数,“//”除完取整

2.将整数转换成字符串处理

class Solution:
    """
    @param number: A 3-digit number.
    @return: Reversed number.
    """
    def reverseInteger(self, number):
        temp = str(number)
        str1 = temp[::-1]
        number = int(str1)
        return number

3.复杂情况可以考虑栈的思想,可是本题使用如下方法显得麻烦

def reverseInteger(self, number):
	number=str(number)#模拟入栈
        l=list(number)
        result=""
        while len(l)>0:
            result+=l.pop()#模拟出栈
        return int(result)

上一篇:洛谷 P3803 【模板】多项式乘法(FFT)


下一篇:[机房测试]10.25