-3

Here is the code for a leetcode algorithm problem:

class Solution {
public:
    int myAtoi(string str) {
        if(str == NULL || str.length() == 0) return 0;
        int pos = true;
        int result = 0;
        int i = 0;
        if(str.charAt(0) == '+' || str.charAt(0) == '-') {
            ++i;
            if(str.charAt(0) == '-') pos = false;
        }
        for(; i != str.length(); ++i) {
            if(str.charAt(i) >= '0' && str.charAt(i) <= '9') {
                result = result*10 + (int)(str.charAt(i)-'0');
            }
        }
        if(!pos) result=-result;
        if(result > INT_MAX) return INT_MAX;
        if(result < INT_MIN) return INT_MIN;
        return result;
    }
};

And I got a Compile Error

Line 4: no match for ‘operator==’ (operand types are ‘std::string {aka std::basic_string<char>}’ and ‘long int’)

So what's wrong with the code?

user2916610
  • 765
  • 1
  • 5
  • 12

2 Answers2

8

str is object of type std::string, not a pointer, it cannot be NULL. Use just str.empty() instead of both checks. There is also no function charAt in string.

ForEveR
  • 55,233
  • 2
  • 119
  • 133
5

NULL is an integer constant, usually defined as 0 or 0L. You cannot compare a string with an int. str.length() == 0 and str.empty() are two good alternatives.

yizzlez
  • 8,757
  • 4
  • 29
  • 44