首页 > 代码库 > Reverse Integer
Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer‘s last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).
1 class Solution { 2 public: 3 int reverse(int x) { 4 5 int flag = 0; 6 if(x < 0) 7 { 8 flag = -1; 9 x = -x;10 }11 12 int result = 0;13 int k = 1;14 vector<int> figure;15 16 while(x / 10 != 0)17 {18 figure.push_back(x % 10);19 x /= 10;20 }21 figure.push_back(x);22 23 for(int i = figure.size()-1; i >= 0; i--, k *= 10)24 {25 result += figure[i] * k;26 }27 28 if(flag == -1)29 result = -result;30 31 return result;32 }33 34 };
Reverse Integer
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。