我正在构建自己的字符串类,我正在尝试使用此函数将数字字符串转换为整数:
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;
}
Run Code Online (Sandbox Code Playgroud)
有些东西不能正常工作,但我无法找出它是什么.当我尝试将"49"转换为int时,它将其转换为134.
^异或.我相信你在找std::pow(10, exp).
甚至这个:
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;
}
Run Code Online (Sandbox Code Playgroud)