9 Dec 2017

write a program in java to convert String to number without using library function.



class StringToNumber
{
       public static void main(String arg[])
       {
              String num="-12345";
              System.out.println(StrToNum(num));
       }
       public static int StrToNum(String str)
       {
              boolean isNegative=false;
              int number=0,i=0;
              if(str.charAt(0)=='-'){
                     isNegative=true;
                     i=1;
              }
              while(i<str.length())
              {
                     number*=10;
                     number+=(str.charAt(i++)-'0');
              }
              if(isNegative)
                     number=-number;
              return number;
       }
}
Output: