2

我正在构建自己的字符串类,并尝试使用此函数将数字字符串转换为整数:

int String::convertToInt() const {  
    int exp = length() - 1;
    int result = 0;

    for(int i = 0; i < length(); ++i) {
        result += (charAt(i) - '0') * (10 ^ exp);
        --exp;
    }   
    return result;
}

有些东西工作不正常,但我无法找出它是什么。当我尝试将“49”转换为 int 时,它会将其转换为 134。

4

3 回答 3

9

^ is XOR. I believe you're looking for std::pow(10, exp).

Or even this:

int String::convertToInt() const {  
    int order = std::pow(10, length() - 1);
    int result = 0;

    for(int i = 0; i < length(); ++i) {
        result += (charAt(i) - '0') * order;
        order /= 10;
    }   
    return result;
}
于 2013-11-01T13:29:07.440 回答
3

最简单的方法是意识到494 * 10 + 9493同样是49 * 10 + 3

也就是说,结果是前N-1个数字加上最后一个数字的10倍。您可以将其编写为循环或递归函数。堆栈深度不会伤害您;大约 20 位数字后,您甚至会溢出 64 位结果。所以

int String::convertToInt() const {
    if (empty()) return 0; // Recursive functions better terminate.
    // TODO: negative numbers.  
    return 10 * convertToInt(substr(0, length()-1)) + (back() - '0');
}

或者

int String::convertToInt() const {
    // TODO: negative numbers.  
    int result = 0;

    for(int i = 0; i < length(); ++i) {
        result * = 10;
        result += (charAt(i) - '0');
    }   
    return result;
}
于 2013-11-01T13:32:49.010 回答
0

更有效的方法是:

// I know you said you are using something else
// but the same principle applies here
std::string s = "12345";

unsigned int result = 0;
unsigned int place = 1;
for (std::size_t i = s.length() - 1; i >= 0; --i, place *= 10)
{
    result += (s[i] - '0') * place;
}

基本上,你从最右边的角色开始,然后向左工作。你向左移动的每个字符,你乘以place10(非常类似于我们大多数人在成长过程中学会做加法的方式:加你的 1...加你的 10...加你的 100...等等)。这也假设您已经知道字符串只包含数字字符('0'-'9')。

于 2013-11-01T14:57:16.643 回答