Skip to content

Instantly share code, notes, and snippets.

@pavelnganpi
Created July 18, 2014 14:02
Show Gist options
  • Save pavelnganpi/77957a6b216fc328e010 to your computer and use it in GitHub Desktop.
Save pavelnganpi/77957a6b216fc328e010 to your computer and use it in GitHub Desktop.
package test;
public class StringToInt {
public static int strToInt( String str ){
int i = 0;
int num = 0;
boolean isNeg = false;
//check for negative sign; if it's there, set the isNeg flag
if( str.charAt(0) == '-') {
isNeg = true;
i = 1;
}
//process each char of the string;
while( i < str.length()) {
num *= 10;
num += str.charAt(i) - '0'; //minus the ASCII code of '0' to get the value of the charAt(i++)
i++;
//System.out.println(str.charAt(i++) - '0');
}
if (isNeg)
num = -num;
return num;
}
public static void main(String[]args){
String n = "123";
System.out.println(strToInt(n));
}
}
@satveersm
Copy link

We should validate our string char may be they not 0-9 so whenever u access a char check it

str[i] >= '0' && str[i] <= 9 then only process it else raise an exception......

so here we done string to int ==> "1234" -->1234

will u try int to string logic

1234 --->"1234" just try it little tricky this your string to int logic.........

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment