007 easy
来源:互联网 发布:山寨币源码 编辑:程序博客网 时间:2024/04/30 00:47
4/29/2015
Meet a very serious problem: overflow when reversed.
As the spoilers say, return 0 when the reversed number overflows.
Solution: 1) use LONG type to store the overflowed result. 2) add judgement of overflow or not before output it
Algorithm 1
(Came by my first thought)
Meet another problem of dealing with overflow number. The problem came with j.
Problem: j is the number 1,10,100… 1,000,000,000. When dealing with the first digit of 3(like 1 when x=1,000,000,003) j=1,000,000,000 from the last loop. but in this loop, sum will be added to 3,000,000,000, theoretically. However, because j overflows as an integer, the result sum in this loop messed up.
Two solutions:
S1: set j as long type
S2: sum=(long ) array[i]j+sum; OR sum=array[i](long) j+sum; use forced type transfer
package happynumber;public class ReverseInteger { public static int reverse (int x) { int i;i=0; //long type is for compare. Only larger range can compare Max and Min Integer long sum=0; int[] array=new int[33]; int number; number=x; if(x<0) number=-x; System.out.println(number); System.out.println(number); while(number!=0) { array[i]=number%10; System.out.println(array[i]); number=number/10; i++; } long j;j=1; i=i-1; for(;i>=0;i--){ sum=array[i]*j+sum; System.out.println(sum); j=j*10; System.out.println(j); } if(x<0) sum=-sum; System.out.println("original result"); System.out.println(sum); if(sum>Integer.MAX_VALUE || sum<Integer.MIN_VALUE) { System.out.println("overflow"); return 0; } else { System.out.println((int)sum); return (int) sum; } } public static void main(String args[]) { int y=0; y=reverse(-1000000003); }}
Algorithm 2: change about calculating result algorithm
package happynumber;public class ReverseInteger2 { public static int reverse (int x) { long result,number; result=0; number=x; if(x<0) number=-number; while(number!=0) { result=result*10+number%10; number=number/10; } if(x<0) result=-result; System.out.println("original result"); System.out.println(result); if(result>Integer.MAX_VALUE || result<Integer.MIN_VALUE){ System.out.println(0); return 0; } else { System.out.println((int)result); return (int) result; } } public static void main(String args[]) { int y=0; y=reverse(1000000003); }}
0 0
- 007 easy
- easy
- Easy
- Easy Plugs
- easy problem
- So Easy!
- so easy
- easy explorer
- Easy Explore
- Easy Task
- Easy Task
- Easy CHM
- HDU2699+Easy
- HDU4648+Easy
- Easy billiards
- Easy STL
- easy connect
- Easy Vpn
- 二次排序代码
- 递归模式的思考(一)
- Android Studio plugin is too old,please...
- 查找(2)——哈希查找
- npm和compass开始一个项目
- 007 easy
- 根据前台设计数据库--搜索页篇
- 苹果CEO乔布斯在斯坦福大学的演讲稿[中英]
- 3、Ext组件Panel面板使用
- Bazel教程
- markdown 文章标签
- 修复TortoiseGit文件夹和文件图标不显示是否修改
- 膨胀和腐蚀操作中的不同结构元效果对比
- Spring Boot Servlet