码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode--Reverse Integer

时间:2014-07-29 22:02:52      阅读:333      评论:0      收藏:0      [点我收藏+]

标签: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)


LeetCode--Reverse Integer,布布扣,bubuko.com

LeetCode--Reverse Integer

标签:leetcode   reverse integer   

原文地址:http://blog.csdn.net/acema/article/details/37535231

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!