Converting String to int without any library function
public static int stringToInt(String number) {
int res = 0;
for (int i = 0; i < number.length(); i++) {
res = res * 10 + number.charAt(i) - '0';
}
return res;
}
Perform whatever calculation you want to perform and then use the following method to convert the int back to String without any library function
Converting int to String without any library function
public static String parseInt(int integer)
{
boolean ifNegative = integer<0;
boolean ifMin = integer == Integer.MIN_VALUE;
StringBuilder builder = new StringBuilder();
integer = ifNegative?(ifMin?Integer.MAX_VALUE:-integer):integer;
List<Integer> list = new LinkedList<Integer>();
int remaining = integer;
int currentDigit = 0 ;
while(true)
{
currentDigit = remaining%10;
list.add(currentDigit);
remaining /= 10;
if(remaining==0) break;
}
currentDigit = list.remove(0);
builder.append(ifMin?currentDigit+1:currentDigit);
for(int c : list)
builder.append(c);
builder.reverse().insert(0, ifNegative?'-':'+');
return builder.toString();
}
Answer from Yousaf on Stack OverflowConverting String to int without any library function
public static int stringToInt(String number) {
int res = 0;
for (int i = 0; i < number.length(); i++) {
res = res * 10 + number.charAt(i) - '0';
}
return res;
}
Perform whatever calculation you want to perform and then use the following method to convert the int back to String without any library function
Converting int to String without any library function
public static String parseInt(int integer)
{
boolean ifNegative = integer<0;
boolean ifMin = integer == Integer.MIN_VALUE;
StringBuilder builder = new StringBuilder();
integer = ifNegative?(ifMin?Integer.MAX_VALUE:-integer):integer;
List<Integer> list = new LinkedList<Integer>();
int remaining = integer;
int currentDigit = 0 ;
while(true)
{
currentDigit = remaining%10;
list.add(currentDigit);
remaining /= 10;
if(remaining==0) break;
}
currentDigit = list.remove(0);
builder.append(ifMin?currentDigit+1:currentDigit);
for(int c : list)
builder.append(c);
builder.reverse().insert(0, ifNegative?'-':'+');
return builder.toString();
}
The source code for Integer.parseInt is available on GrepCode. It uses a package-private method to generate NumberFormatException errors, but you can leave those out and the code will still work for valid strings.
public static int parseInt(String s, int radix) {
int result = 0;
boolean negative = false;
int i = 0, len = s.length();
int limit = -Integer.MAX_VALUE;
int multmin;
int digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') {
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
}
i++;
}
multmin = limit / radix;
while (i < len) {
digit = Character.digit(s.charAt(i++), radix);
result *= radix;
result -= digit;
}
}
return negative ? result : -result;
}
And what is wrong with this?
int i = Integer.parseInt(str);
EDIT :
If you really need to do the conversion by hand, try this:
public static int myStringToInteger(String str) {
int answer = 0, factor = 1;
for (int i = str.length()-1; i >= 0; i--) {
answer += (str.charAt(i) - '0') * factor;
factor *= 10;
}
return answer;
}
The above will work fine for positive integers - assuming that the string only contains numbers, otherwise the result is undefined. If the number is negative you'll have to do a little checking first, but I'll leave that as an exercise for the reader.
If the standard libraries are disallowed, there are many approaches to solving this problem. One way to think about this is as a recursive function:
- If n is less than 10, just convert it to the one-character string holding its digit. For example, 3 becomes "3".
- If n is greater than 10, then use division and modulus to get the last digit of n and the number formed by excluding the last digit. Recursively get a string for the first digits, then append the appropriate character for the last digit. For example, if n is 137, you'd recursively compute "13" and tack on "7" to get "137".
You will need logic to special-case 0 and negative numbers, but otherwise this can be done fairly simply.
Since I suspect that this may be homework (and know for a fact that at some schools it is), I'll leave the actual conversion as an exercise to the reader. :-)
Hope this helps!
String myString = "1234";
int foo = Integer.parseInt(myString);
If you look at the Java documentation you'll notice the "catch" is that this function can throw a NumberFormatException, which you can handle:
int foo;
try {
foo = Integer.parseInt(myString);
}
catch (NumberFormatException e) {
foo = 0;
}
(This treatment defaults a malformed number to 0, but you can do something else if you like.)
Alternatively, you can use an Ints method from the Guava library, which in combination with Java 8's Optional, makes for a powerful and concise way to convert a string into an int:
import com.google.common.primitives.Ints;
int foo = Optional.ofNullable(myString)
.map(Ints::tryParse)
.orElse(0)
For example, here are two ways:
Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);
There is a slight difference between these methods:
valueOfreturns a new or cached instance ofjava.lang.IntegerparseIntreturns primitiveint.
The same is for all cases: Short.valueOf/parseShort, Long.valueOf/parseLong, etc.
To improve your intToString() method you should consider using a StringBuilder, and specifically the method StringBuilder.append(int).
Iterate digits in your int, and for each digit you can append(eachDigit) to the StringBuilder element. This will also reduce the complexity of intToString() to \$O(n)\$ since you do not need to create a new String instance each iteration. To get a String object from the StringBuilder, use StringBuilder.toString(). Or, if you are not allowed, you can use StringBuilder.subString(0).
You should also use a StringBuilder.append() (using the same idea) to reverse the resulting string (your second loop in your code).
Since it is not homework (as per comments), I have no problems providing a code snap. It should look something like this:
public static String intToString(int n) {
if (n == 0) return "0";
StringBuilder sb = new StringBuilder();
while (n > 0) {
int curr = n % 10;
n = n/10;
sb.append(curr);
}
String s = sb.substring(0);
sb = new StringBuilder();
for (int i = s.length() -1; i >= 0; i--) {
sb.append(s.charAt(i));
}
return sb.substring(0);
}
Notes:
- You can also use
StringBuilder.reverse()instead of the second loop. - In here, \$O(n)\$ means linear in the the number of digits in the input number (
nis the number of digits in the input number - not the number itself!) If you are looking for the complexity in terms of the initial number (it is \$O(\log(n))\$) since you divide your element by 10 each iterations, you have a total of \$\log_{10}(\text{number})\$ iterations for each loop, which results in \$O(\log(\text{number}))\$.
For your example , I should point out some problems : first , when you add two add string frequently, you should use StringBuilder instead ; second , you should consider Integer.MIN_VALUE into account!Here is my code:
public static String parseInt(int integer)
{
boolean ifNegative = integer<0;
boolean ifMin = integer == Integer.MIN_VALUE;
StringBuilder builder = new StringBuilder();
integer = ifNegative?(ifMin?Integer.MAX_VALUE:-integer):integer;
List<Integer> list = new LinkedList<Integer>();
int remaining = integer;
int currentDigit = 0 ;
while(true)
{
currentDigit = remaining%10;
list.add(currentDigit);
remaining /= 10;
if(remaining==0) break;
}
currentDigit = list.remove(0);
builder.append(ifMin?currentDigit+1:currentDigit);
for(int c : list)
builder.append(c);
builder.reverse().insert(0, ifNegative?'-':'+');
return builder.toString();
}