Ручное преобразование строки в целое число в Java - PullRequest
14 голосов
/ 17 января 2012

У меня есть строка, состоящая из последовательности цифр (например, "1234").Как вернуть String как int без использования библиотечных функций Java, таких как Integer.parseInt?

public class StringToInteger {
  public static void main(String [] args){
    int i = myStringToInteger("123");
    System.out.println("String decoded to number " + i);
  }

  public int myStringToInteger(String str){
      /* ... */
  }
}

Ответы [ 15 ]

0 голосов
/ 23 декабря 2015

Может быть, этот путь будет немного быстрее:

public static int convertStringToInt(String num) {
     int result = 0;

     for (char c: num.toCharArray()) {
        c -= 48;
        if (c <= 9) {
            result = (result << 3) + (result << 1) + c;
        } else return -1;
    }
    return result;
}
0 голосов
/ 15 июля 2015
public static int convertToInt(String input){
        char[] ch=input.toCharArray();
        int result=0;
        for(char c : ch){
            result=(result*10)+((int)c-(int)'0');
        }
        return result;
    }
0 голосов
/ 10 мая 2015
public int myStringToInteger(String str) throws NumberFormatException 
{
    int decimalRadix = 10; //10 is the radix of the decimal system

    if (str == null) {
        throw new NumberFormatException("null");
    }

    int finalResult = 0;
    boolean isNegative = false;
    int index = 0, strLength = str.length();

    if (strLength > 0) {
        if (str.charAt(0) == '-') {
            isNegative = true;
            index++;
        } 

        while (index < strLength) {

            if((Character.digit(str.charAt(index), decimalRadix)) != -1){   
                finalResult *= decimalRadix;
                finalResult += (str.charAt(index) - '0');
            } else throw new NumberFormatException("for input string " + str);

            index++;
        }

    } else {
        throw new NumberFormatException("Empty numeric string");
    }

    if(isNegative){
        if(index > 1)
            return -finalResult;
        else
            throw new NumberFormatException("Only got -");
    }

    return finalResult;
}

Результат: 1) Для ввода «34567» конечный результат будет: 34567 2) Для ввода «-4567» конечный результат будет: -4567 3) Для ввода "-" конечный результат будет: java.lang.NumberFormatException: только получил - 4) Для ввода "12ab45" конечный результат будет: java.lang.NumberFormatException: для входной строки 12ab45

0 голосов
/ 17 января 2012

Используйте тот факт, что Java использует char и int одинаково. В основном, выполните char - '0', чтобы получить значение типа char.

public class StringToInteger {
    public static void main(String[] args) {
        int i = myStringToInteger("123");
        System.out.println("String decoded to number " + i);
    }

    public static int myStringToInteger(String str) {
        int sum = 0;
        char[] array = str.toCharArray();
        int j = 0;
        for(int i = str.length() - 1 ; i >= 0 ; i--){
            sum += Math.pow(10, j)*(array[i]-'0');
            j++;
        }
        return sum;
    }
}
0 голосов
/ 17 января 2012

Используйте это:

static int parseInt(String str) {
    char[] ch = str.trim().toCharArray();
    int len = ch.length;
    int value = 0;
    for (int i=0, j=(len-1); i<len; i++,j--) {
        int c = ch[i];
        if (c < 48 || c > 57) {
            throw new NumberFormatException("Not a number: "+str);
        }
        int n = c - 48;
        n *= Math.pow(10, j);
        value += n;
    }
    return value;
}

И, кстати, вы можете обрабатывать особый случай отрицательных целых чисел, в противном случае он выдаст исключение NumberFormatException .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...