Home > Mobile >  how i can convert char array to int without use parseInt and String.valueOf() (java)
how i can convert char array to int without use parseInt and String.valueOf() (java)

Time:05-13

need to convert char array to int without use parseInt and String.valueOf(),

need to realize this method

public static int parseInt(char[] str) {
  
}

for example, if the input data is char[] str = {'-','1','2','3'};

need to show:

int result = parseInt(str);

System.out.println(result); // -123

CodePudding user response:

It is going to work for your case

public static int parseInt(char[] str) {
        int result = 0;
        int start = 0;
        boolean negative = false;
        if(str[0] == '-') {
            start = 1;
            negative = true;
        }
        for (int i = start; i < str.length; i  )
        {
            
            int digit = (int)str[i] - (int)'0';
            if ((digit < 0) || (digit > 9)) throw new NumberFormatException();
            result *= 10;
            result  = digit;
        }
        if(negative) {
            result = 0 - result;
        }
        return result;
    }

CodePudding user response:

public static void main(String[] args) {
    char[] str = {'-', '1', '2', '3'};
    int[] charToInt = new int[str.length];
    for (int i = 0; i < str.length; i  ) {
        charToInt[i] = Character.getNumericValue(str[i]);
    }
    System.out.println(Arrays.toString(charToInt));
}

Mb something like this, but I'm not sure about the first character

  • Related