首页 > 代码库 > LeetCode--Reverse Integer

LeetCode--Reverse Integer

Reverse Integer

 
Total Accepted: 21990 Total Submissions: 55259

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

Have you been asked this question in an interview?


解题思路

注意负数和00的处理:
例如:
-2345
-23000
4
-3
0

源代码:

JAVA 源代码:

public class Solution {
     public long reverse(int x) {
		String str = String.valueOf(x);
		StringBuilder sb=new StringBuilder();
		boolean flag=true;
		for( int i=str.length()-1; i>0; --i){
			if (flag==true && str.charAt(i) == '0' ){
				continue;
			}else{
				flag=false;
			}
			sb.append(str.charAt(i));			
		}
		if(str.charAt(0)== '-'){
			sb.insert(0, '-');
		}else{
			sb.append(str.charAt(0));
		}
		return Long.valueOf(sb.toString());		
	}
}

C++ 源代码:

class Solution {
public:
    int reverse(int x) {
        int r = 0; 
        for( ; x ; x/=10){
            r= r*10 + x%10;
        }
        return r;
    }
};


Python代码

(第一个python练习代码)
class Solution:
    # @return an integer
    def reverse(self, x):
        s=''    
        ix = 0  
        x = str(x)
        if x[0] == '-': 
            s += x[0] 
            ix = 1  
        beg=len(x)-1
        while (x[beg] == '0' and beg > 0):
            beg -= 1
    
        if ix == 0 :
            s += x[beg::-1]
        else:   
            s += x[beg:0:-1]    
        return int(s)