有人可以详细解释这个回文代码是如何工作的吗?
Could someone explain in detail on how this palindrome code works?
#include <iostream>
// Define is_palindrome() here:
bool is_palindrome(std::string text) {
std::string reversed_text = "";
for (int i = text.size() - 1; i >= 0; i--) {
reversed_text += text[i];
}
if (reversed_text == text) {
return true;
}
return false;
}
int main() {
std::cout << is_palindrome("madam") << "n";
std::cout << is_palindrome("ada") << "n";
std::cout << is_palindrome("lovelace") << "n";
}
有人可以详细地向我解释这个 for 循环是如何工作的吗?我想知道代码如何对每个字母进行排序,以确定该单词是否是回文。
首先,我们定义 is_palindrome 函数来返回布尔值。我们的输入字符串是函数参数。
然后,我们使用以下 for 循环反转文本。
std::string reversed_text = "";
for (int i = text.size() - 1; i >= 0; i--) {
reversed_text += text[i];
}
此代码仅定义一个名为 reversed_string 的字符串。然后,它一次反转一个字母的输入字符串(text[i]
在输入字符串中给出 i+1 字母,reversed_text += text[i]
将此字母添加到字符串中(。
之后,代码是一个简单的 if 语句。它比较原始字符串和反向字符串。如果两者相同,则该函数返回 true。如果它们不同,则函数返回 false。
if (reversed_text == text) {
return true;
}
return false;
}
阅读代码的能力远比编写代码的能力重要,因为在你编程生涯的大部分时间里,你阅读的次数比编写的要多得多。通常情况下,它是别人的代码。如果你缺乏技能,你将很难在这个领域工作。
下面是上面的函数体注释:
// prepare a string variable to hold the reversed input
std::string reversed_text = "";
// append each character from the input to variable above, starting from the last character, effectively generating its reversed version
for (int i = text.size() - 1; i >= 0; i--) {
reversed_text += text[i];
}
// it's a palindrome if the reversed input is the same as the input
if (reversed_text == text) {
return true;
}
// not a palindrome otherwise
return false;
相关文章:
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- <<操作员在下面的行中工作
- 有人能解释一下为什么下界是这样工作的吗C++的
- ExtractIconEx:可以工作,但偶尔会崩溃
- C++中的memset函数工作不正常
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 链表c++插入,所有情况都已检查,但没有任何工作
- 当 int 方法工作正常时,void 方法有何不同,或者为什么我不能调用 void 方法?