7. Reverse Integer
  • Description
  • O(n)
    #!/usr/bin/python
    
    def reverse(x):
        a = str(x)
        l = []
        sign = '';
        for c in a:
            if c == '-':
                sign = c
                continue
            l.append(c);
    
        l.reverse();
    
        while len(l) > 1:
            c = l.pop();
            if c != '0':
                l.append(c)
                break
    
        n = int(sign+''.join(l));
    
        if n < -2**31 or n > 2**31-1:
            return 0
        else:
            return n
    
    if __name__ == '__main__':
        print reverse(123)
        print reverse(-123)
        print reverse(120)
        print reverse(1534236469)
    			
    #!/usr/bin/python
    
    def reverse(x):
        sign = False
        if x < 0:
            sign = True
    
        re = 0
        x = abs(x)
        while x > 0:
            re = re*10 + x%10
            print re
            x = x/10
    
        if sign:
            re = 0 - re
    
        if re < -2**31 or re > 2**31-1:
            return 0
        else:
            return re
    
    if __name__ == '__main__':
        print reverse(123)
        print reverse(-123)
        print reverse(120)
        print reverse(1534236469)
        print reverse(0)
    			
    #!/usr/bin/python
    
    def reverse(x):
        if x == 0:
            return 0;
    
        sign = ''
        if x < 0:
            sign = '-'
    
        a = str(x)
    
        start = False
        l = []
    
        for i in xrange(len(a)-1, -1, -1):
            if not start and a[i] != '0':
                start = True
            if start and a[i] != '-':
                l.append(a[i]);
    
        n = int(sign+''.join(l));
    
        if n < -2**31 or n > 2**31-1:
            return 0
        else:
            return n
    
    if __name__ == '__main__':
        print reverse(123)
        print reverse(-123)
        print reverse(120)
        print reverse(1534236469)
        print reverse(0)