Advertisement
sweet1cris

Untitled

Jan 9th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.78 KB | None | 0 0
  1. //version 1(use library function)
  2. public class Solution {
  3.     /**
  4.      * @param str a string
  5.      * @return an integer
  6.      */
  7.     public int stringToInteger(String str) {
  8.         return Integer.valueOf(str);
  9.     }
  10. }
  11.  
  12. //version 2
  13. public class Solution {
  14.     /**
  15.      * @param str a string
  16.      * @return an integer
  17.      */
  18.     public int stringToInteger(String str) {
  19.         // Write your code here
  20.         int integer = 0;
  21.         int Minus = 0;
  22.        
  23.         if (str.charAt(0) == '-'){
  24.             Minus = 1;
  25.         }
  26.        
  27.         for (int i = Minus; i < str.length(); i++){
  28.             integer = integer * 10 + str.charAt(i)-'0';
  29.         }
  30.        
  31.         if (Minus == 1){
  32.             integer = -integer;
  33.         }
  34.         return integer;
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement