首页
学习
活动
专区
圈层
工具
发布

长溢流
EN

Stack Overflow用户
提问于 2022-09-25 06:05:45
回答 1查看 66关注 0票数 1

我一直在编写一个将字符串转换为整数的小程序。我启动了这个程序,我首先尝试保存在一个数组中,但是程序不起作用。它只迭代一次,没有错误。我试过了,但我认为当我在array.You中存储字符串时,将字符串减去48,就会出现错误。

对不起,这是一条经过编辑的消息,程序运行正常,但是当我输入-“-91283472332”(按照leetcode)时,我得到了错误的答案。

你可以亲眼看到-

代码语言:javascript
复制
#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;

}
EN

回答 1

Stack Overflow用户

发布于 2022-09-25 06:55:18

您的解决方案比需要的要复杂得多。

我们可以使用指针算法对字符串进行迭代,并为for循环包含一个条件,该条件在字符串末尾或当前字符不再是数字时自动终止。

可以通过在每个循环中将其乘以10并将当前数字的数字值添加到其中来构建result

一个负号可以通过检查第一个字符来容纳。这是'-',我们可以将标志negative设置为1作为true,并在第一个字符之后增加str指针。在函数的末尾,我们可以根据该标志确定是生成-result还是result

代码语言:javascript
复制
#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;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73842363

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档