算法#23--整数反转
来源:互联网 发布:运动仿真软件哪个好 编辑:程序博客网 时间:2024/05/01 07:30
Reverse digits of an integer.
Example1: x = 123, return 321Example2: x = -123, return -321Example3: x = -12300, 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?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
My code:
public static int Reverse(int x) { string s = x.ToString(); char[] arr = s.ToArray(); int start, end = s.Length; if (x == 0) { return 0; } start = (x > 0) ? 0 : 1; for (int i = arr.Length - 1; i >= 0; i--) { if (arr[i] != '0') { end = i; break; } } char[] data = new char[end - start + 1]; int index = 0; for (int i = end; i >=start ; i--) { data[index++] = arr[i]; } string buf = new string(data); int value; bool successful = int.TryParse(buf, out value); if (successful) { return (x > 0) ? value : -1 * value; } else { return 0; \\throw new Exception(); } }
Best code:
public static int Reverse(int x) { int result = 0; while (x != 0) { int tail = x % 10; int newResult = result * 10 + tail; if ((newResult - tail) / 10 != result)//If overflow exists, the new result will not equal previous one. { return 0; } result = newResult; x = x / 10; } return result; }
0 0
- 算法#23--整数反转
- 整数反转的递归算法
- 整数反转算法(php实现)
- C语言实现整数反转-简练算法
- 算法题:整数反转reverse integer
- 算法---将一个整数反转(简单)
- 反转整数
- 反转整数
- 反转整数
- 整数反转
- 反转整数
- 整数反转
- 反转整数
- 整数反转
- 反转整数
- 反转整数
- 反转整数
- 反转整数
- 网络中我关注的那些前辈们的档案(2016.12.28 Updating...)
- MySQL和Oracle的delete,truncate
- 在GridView或者ListView的Adapter中使用Glide加载图片,图片被拉伸问题
- 开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推
- dfs的剪枝问题
- 算法#23--整数反转
- SpringMVC 提交参数的方式和注解详述
- Logstash实践: 分布式系统的日志监控
- 安卓shadow综合控件和布局
- 使用eclipse连接mysql database explorer连接不上的解决办法以及配置
- Android 中使用IDE为Android Studio时候,后台类型从double 改成 int,但是客户端还是显示double问题(JAVA修改Model类型,但是无效)
- C++ 头文件格式和函数注释格式
- 如何使用百度加固服务
- 计算机图书