Fad*_*dwa 0 c++ string integer
我有一串数字,我想将这些数字相乘
string myS = "731671765313";
int product = 1;
for(int i = 0; i<myS.length(); i++)
product *= myS[i];
Run Code Online (Sandbox Code Playgroud)
如何将字符串元素转换为 int 因为结果完全错误。我尝试将其转换为int但徒劳无功。
使用std::accumulate(因为您正在累积元素的乘积,因此它使意图清晰)并回想它'0'不是 0,而是数字字符是连续的。例如,在 ASCII 中,'0'是 48,'1'是 49 等等。因此,减法'0'会将那个字符(如果是数字)转换为适当的数值。
int product = std::accumulate(std::begin(s), std::end(s), 1,
[](int total, char c) {return total * (c - '0');}
);
Run Code Online (Sandbox Code Playgroud)
如果你不能使用 C++11,它很容易被替换:
int multiplyCharacterDigit(int total, char c) {
return total * (c - '0');
}
...
int product = std::accumulate(s.begin(), s.end(), 1, multiplyCharacterDigit);
Run Code Online (Sandbox Code Playgroud)
如果这些都不是一个选项,那么你所拥有的几乎就在那里:
int product = 1;
for(int i = 0; i<myS.length(); i++)
product *= (myS[i] - '0');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7667 次 |
| 最近记录: |