title: Convert String to Long,No built in library
body: <p>I wrote Java code to convert <code>String</code> to <code>long</code>. However, when dealing with overflow problem, I don't have clues how to solve it. If a number is overflowed, computer believe every number is legal in storage. <strong>How to let program, with 64bit jdk ,detect the real number is overflowed is the key problem</strong>. And I'm not allowed to use any built-in library such as parseLong or others.</p>
  
  <pre><code>public static long strTolong(String s){
          //error checking
          if(s == null) return 0;
          s = s.trim();//remove all space character
          boolean neg = false;//judge the number is negative or positive
          int pos = 0 ; //index of string
          long result = 0;
          //check positive or negative
          if(s.charAt(pos) == '-'){
              neg = true;
              pos++;
          }else if(s.charAt(pos) == '+') pos++;
  
          //calculate result
          while(pos&lt;s.length()){
              if(s.charAt(pos) &gt;='0' &amp;&amp; s.charAt(pos) &lt;='9'){
                  result = result*10+(s.charAt(pos) - '0');
              }else
                  break;
              pos++;
          }
          if(neg) result =-result;
  
          //check overflow
          if(result &gt;Long.MAX_VALUE) {
              return Long.MAX_VALUE;
          }
          if(result&lt;Long.MIN_VALUE){
              return Long.MIN_VALUE;
          }
  
  
          return result;
      }
  </code></pre>
  
  <p>If <strong>data is larger than <code>long.maxvalue</code></strong>, the result can't be stored in computer correctly.</p>
  
  <p>How to solve this problem?</p>