首页 > 其他 > 详细

LeetCode--Reverse Integer

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!