2

I am writing an Atoi function in Java. It runs fine for +ve integers. But what I want is when I enter a negative integer it should give me an error. So I tried including continue statement in my class Atoi. The class implemented is:

class Atoi {

    int atoi(String tmp) {

    int result = 0;

        for (int i = 0; i < tmp.length(); i++) {

            char digit = (char)(tmp.charAt(i) - '0');

        if(digit == '-')

        continue;
        }

        else {

            result += (digit * Math.pow(10, (tmp.length() - i - 1)));
        }

    return result;

    }
}   

But unfortunately it gives me the negative equivalent of the character i.e for -12 it gives me 655312! Help.

EDIT: Suppose I need to check for floating point numbers what should I do? If I enter 12.1 or 123.2 it should return 12.1 and 123.2 repectively!!

Andy Jazz
  • 49,178
  • 17
  • 136
  • 220
Rebooting
  • 2,762
  • 11
  • 47
  • 70

6 Answers6

2

Instead of continue you should give an error (throw an exception, return -1 or whatever you mean with "give an eror").

If you want to ignore the - you can change the else clause to:

result = digit + result * 10;
Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
  • +1 That is far more elegant (and quick), than using Math.pow in each iteration. Though this thinking requires getting used to... But the real problem is, he does want to deal with negative numebrs too! – ppeterka Nov 06 '12 at 13:40
  • Suppose I need to check for floating point numbers what should i do ? if i enter 12.1 or 123.2 it should return 12.1 and 123.2 repectively!! – Rebooting Nov 06 '12 at 14:48
1

Quick fix for the obvious problem: the order of the logic was wrong...

Instead of

    char digit = (char)(tmp.charAt(i) - '0');
    if(digit=='-')
    continue;

try

    char origChar=tmp.charAt(i);
    if(origChar=='-')
        continue;
    char digit = (char)(origChar - '0');

But there are two more problems:

  • it does not negate the value, in case of a '-' character is present!
  • what if this is the input string: -1-2-3-4-5? The result will be interesting! EDIT: try this input also: 'répa'... Even more interesting result!

Don't forget to test with incorrect inputs too, and as @Klaus suggested, don't hesitate to throw an exception, (preferably IllegalArgumentException) with a correct error message, if an incorrect input is given to the function...

ppeterka
  • 20,583
  • 6
  • 63
  • 78
  • 1st case is solved .. i used a variable "negative" initialised to 0. If a - occurs, it is incremented by 1.. so if negative ==1, a - sign occurs before the number.. second problem still trying to figure out! will accept ur answ in 11 mins! ;) – Rebooting Nov 06 '12 at 13:41
  • Hint: I think only the first character can be a '-', this information could be used... – ppeterka Nov 06 '12 at 13:43
  • Suppose I need to check for floating point numbers what should i do ? if i enter 12.1 or 123.2 it should return 12.1 and 123.2 repectively!! – Rebooting Nov 06 '12 at 14:11
  • You should check for '.' character, and after that is encountered, add the fractions to the result. – ppeterka Nov 07 '12 at 09:02
1

You can write code like this, of course, but you need to check that tmp is a valid number.

int atoi(String tmp) {

    int result = 0;

    int factor = tmp.charAt(0) == "-" ? -1 : 1;

        for (int i = 0; i < tmp.length(); i++) {

            if (tmp.chatAt(i) < '0' ||  tmp.chatAt(i) > '9') 

                continue;

                char digit = (char)(tmp.charAt(i) - '0');

                result += (digit * Math.pow(10, (tmp.length() - i - 1)));
        }

        return result * factor;
}
Eric
  • 6,563
  • 5
  • 42
  • 66
user902383
  • 8,420
  • 8
  • 43
  • 63
1

If this is not being done as a programming exercise, there is a simpler solution:

  static int atoi(String tmp)
  {
      int result = Integer.parseInt(tmp);
      if(result >= 0) {
         return result;
      } else {
         throw new IllegalArgumentException("Negative string "+"\"" + tmp + "\"");
      }
  }

Substitute the appropriate exception or other action in the negative result case. If you want to just ignore '-', as in the posted code, replace the if-then-else with:

      return Math.abs(result);

This code also throws an exception for strings like "abc".

More generally, if a library method does not do exactly what you want, it is often easy to use it in a method that modifies its behavior, rather than re-writing it.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75
0

If you don't want to convert negative numbers then simply return 0 whenever you encounter - sign instead of looping further. Put this code before the if-else block.

     if(tmp.charAt(i)=='-')  
         return 0;
Abubakkar
  • 15,488
  • 8
  • 55
  • 83
0
if(digit=='-')

With

(char)(tmp.charAt(i)

You're code is assuming there are no -'s

(char)(tmp.charAt(i) - '0');

Is an optimization that's blindly clamping the 'digit' variable to a number.

You need to step through what your code is actually doing, search for an ASCII chart and work through what the subtractions of '0' does ('0' == 48), so '1' (49) - '0' (48) = 1 etc...

Louis Ricci
  • 20,804
  • 5
  • 48
  • 62