Long Long overflow

75 Views Asked by At

I have been working on a small program that converts strings into integers. I started the program and I was first trying to save in an array but the program is not working. Its iterating only once and there is no error.I tried it but I think the error is at when I convert the string by subtracting it by 48 in storing it in the array.You can see the code

Sorry this is an edited message tnow the program is working properly but when I give input -"-91283472332"(as per leetcode) I am getting a wrong answer

you can see for yourself - enter image description here

#include <stdio.h>

int myAtoi(char *s)
{
    int i = 0;           // for iterating the character
    int isNegative = 0; // for checking if the umber is negative
    long long res = 0;         // for result
    while (s[i] != '\0')
    {
    printf("%d\n",res);
        if (48 <= s[i] && s[i]<= 57)
        {
            res=(res*10)+(s[i]) - 48;
        }
        else if (s[i] == 45)
        {
            isNegative = 1;
        }
        else if (s[i] == ' ')
        {
            ;
        }
        else
        {
            break;
        }

        i++;
    }
    if (isNegative)
    {
        res = res-(res*2);
    }
    printf("%d",res);
    return res;
}



int main()
{
    char a[] = "-91283472332";
    myAtoi(a);
    return 0;

}
1

There are 1 best solutions below

1
Chris On

Your solution is rather more complex than it needs to be.

We can use pointer arithmetic to iterate over the string, and include a condition for our for loop that automatically terminates at the end of the string or when the current character is no longer a digit.

The result can be built up by multiplying it by ten on each loop and adding the current digit's numeric value to it.

A negative sign can be accommodated by checking the first character. It's it's '-' we can set a flag negative to 1 for true and increment the str pointer past the first character. At the end of the function, we can determine whether to result -result or result based on that flag.

#include <string.h>
#include <stdio.h>
#include <ctype.h>

int my_atoi(char *str) {
    int result = 0;
    int negative = 0;    

    if (*str == '-') {
        negative = 1;
        str++;
    }

    for (; *str && isdigit(*str); str++) {
        result *= 10;
        result += *str - '0';
    }

    return negative ? -result : result;
}

int main(void) {
    char foo[] = "3456gfghd";

    printf("%d\n", my_atoi(foo));

    return 0;
}