fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. String a = "2147483647";
  13. System.out.println("Integer : " + atoi(a));
  14. }
  15.  
  16. public static int atoi(String a) throws Exception
  17. {
  18. String sane = checkSanity(a);
  19. if( sane == null )
  20. {
  21. throw new Exception("Not compatible");
  22. }
  23.  
  24. if( sane.length() > 10 )
  25. {
  26. throw new Exception("Overflow");
  27. }
  28.  
  29. if( sane.length() <= 0 )
  30. {
  31. throw new Exception("Underflow");
  32. }
  33.  
  34. int convertedInt = 0;
  35. int exponent = 0;
  36. for( int i = sane.length() - 1; i >= 0 ; i-- )
  37. {
  38. int newDigit = Character.getNumericValue( sane.charAt(i) );
  39.  
  40. int newValueToAdd = (int) ( Math.pow(10, exponent) * newDigit );
  41.  
  42. if( convertedInt <= Integer.MAX_VALUE - newValueToAdd )
  43. {
  44. convertedInt += newValueToAdd;
  45. }
  46. else
  47. {
  48. throw new Exception("Overflow");
  49. }
  50.  
  51. exponent++;
  52. }
  53.  
  54. return convertedInt;
  55. }
  56.  
  57. public static String checkSanity(String a)
  58. {
  59. // could be null
  60. if( a == null )
  61. {
  62. return null;
  63. }
  64.  
  65. // Trim leading and trailing spaces.
  66. String b = a.trim();
  67.  
  68. // Should it have + or - symbol, consider.
  69. String c;
  70. if( b.charAt(0) == '+' || b.charAt(0) == '-' )
  71. {
  72. c = b.substring(1);
  73. }
  74. else
  75. {
  76. c = b.substring(0);
  77. }
  78.  
  79. // could have special characters and non numbers.
  80. for( int i = 0; i < c.length(); i++ )
  81. {
  82. if( ! Character.isDigit(c.charAt(i)) )
  83. {
  84. return null;
  85. }
  86. }
  87.  
  88. return c;
  89. }
  90. }
Runtime error #stdin #stdout #stderr 0.1s 320256KB
stdin
Standard input is empty
stdout
converted so far: 8
converted so far: 48
converted so far: 648
converted so far: 3648
converted so far: 83648
converted so far: 483648
converted so far: 7483648
converted so far: 47483648
converted so far: 147483648
stderr
Exception in thread "main" java.lang.Exception: Overflow
	at Ideone.atoi(Main.java:46)
	at Ideone.main(Main.java:13)