我需要构建一个函数来计算 C++ 中的一串数字。数字串在 balanced ternary 中形式表示数字为 -1、0 或 1 有效。所以函数的重点是检查字符串以确保它是有效的。例如,如果用户输入“-101-11”,则 bool 函数将返回 true。或者,如果用户输入“-1012”,则 bool 函数将返回 false。这个函数也是一个类的私有(private)成员函数。让我向您展示到目前为止我编写的代码(我知道这是不正确的,但如果有人能帮助我,那就太好了!)它是用 C++ 编写的。
bool BTernary::isTernary(string s)
{
int i;
int l = s.length();
for (i = 0; i < l; i++) {
if (s.at(i) == '-') {
continue;
}
else if (s.at(i) == '0') {
continue;
}
else if (s.at(i) == '1') {
break;
}
return true;
}
return false;
}
我还尝试了一种不同的方法来检查字符串,它看起来像这样:(这是我已经处理了一段时间的测试文件,它编译没有错误。问题是如果它看到一个 ' -' 或 '1' 或 '0' 它会自动假定它为真,我想我不是评估整个字符串的字符,而是逐个字符评估?
#include <iostream>
#include <string>
using namespace std;
int main()
{
int i;
string s = "0";
for (i = 0; i < s.length(); i++) {
if (s.at(i) == '-' || '0' || '1') {
cout << "True" << endl;
return True;
}
else {
cout << "false" << endl;
return false;
}
}
}
最佳答案
这是 Mihail 建议的精简版:
bool BTernary::isTernary(const std::string& s)
{
bool minus = false;
for (const char c : s)
{
switch (c)
{
case '-':
if (minus) return false;
minus = true;
break;
case '0':
if (minus) return false;
break;
case '1':
if (minus) minus = false;
break;
default:
return false;
}
return !minus;
}
关于c++ - 评估字符串的 bool 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58289472/