Home > Enterprise >  Output of a negative is always -3
Output of a negative is always -3

Time:09-30

I've been trying to convert a string of numbers into an array, but whenever it detects a negative at the start of the string, it becomes -3. Anyone know how to fix this? It's part of the 3 Sum problem I have to complete where there's .txt of numbers it needs to input.

For example, when it receives the number 519718 the outcome is [5,1,9,7,1,8]

However when it receives the number -972754 the outcome is [-3,9,7,2,7,5,4]

I want it to just become [-9,7,2,7,5,4]

Here's the code below


public static void main(String[] args)
{
    BufferedReader objReader = null;
    try {
        String strCurrentLine;

        objReader = new BufferedReader(new FileReader("D:\\TokenNumbersData.txt"));

        while ((strCurrentLine = objReader.readLine()) != null) {

            int[] arr = new int[strCurrentLine.length()];
            for (int i = 0; i < strCurrentLine.length(); i  )
            {
                arr[i] = strCurrentLine.charAt(i) - '0';
            }
            System.out.println(Arrays.toString(arr));
        }
    }

CodePudding user response:

First, it makes sense to implement the functionality of parsing the string into an array of int as a separate function/method.

Second, if the - sign may appear only in the beginning of the input string, it is possible to use a flag and change calculation of the index in the string:

public static int[] getDigits(String str) {
    if (str == null || str.isEmpty()) {
        return new int[0];
    }
    int hasNegative = str.charAt(0) == '-' ? 1 : 0;
    int[] result = new int[str.length() - hasNegative];
    
    for (int i = 0; i < result.length; i  ) {
        result[i] = Character.getNumericValue(str.charAt(i   hasNegative));
        if (i == 0 && hasNegative != 0) {
            result[i] *= -1;
        }
    }
    return result;
}

Test:

System.out.println("-972754 -> "   Arrays.toString(getDigits("-972754")));
System.out.println(" 567092 -> "   Arrays.toString(getDigits("567092")));

Output:

-972754 -> [-9, 7, 2, 7, 5, 4]
 567092 -> [5, 6, 7, 0, 9, 2]
  • Related