Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Subscribe to see which companies asked this question
两种方法,第一种比较耗时间,应该是在转换为字符串的时候浪费了时间
class Solution { public: void reverse_str(string &s, int begin, int end) { int i ,j; char c; for (i=begin,j=end;i<j;i++,j--) { c = s[i]; s[i] = s[j]; s[j] = c; } } int reverse(int x) { if (x>=0 && x<=9) return x; stringstream ss; ss << x; string str = ss.str(); int len = str.size(); if (x > 0) { reverse_str(str,0,len-1); } else { reverse_str(str,1,len-1); } stringstream sss(str); double r =0; sss >> r; if (r>INT_MAX || r<INT_MIN) { r = 0; } return (int)r; } };
class Solution { public: void reverse_str(string &s, int begin, int end) { int i ,j; char c; for (i=begin,j=end;i<j;i++,j--) { c = s[i]; s[i] = s[j]; s[j] = c; } } int reverse(int x) { if (x>=0 && x<=9) return x; stringstream ss; ss << x; string str = ss.str(); int len = str.size(); if (x > 0) { reverse_str(str,0,len-1); } else { reverse_str(str,1,len-1); } stringstream sss(str); double r =0; sss >> r; if (r>INT_MAX || r<INT_MIN) { r = 0; } return (int)r; } };
原文:http://www.cnblogs.com/SpeakSoftlyLove/p/5097307.html