我確信這段代碼并不完美,但我是編程新手,并且正在嘗試解決檢查數字是否為回文的挑戰。我嘗試在代碼中撰寫一個布爾型函式,如果數字是回文則回傳“真”,否則回傳“假”。
無論如何,跳到背景關系,我希望每次計算機注意到回文主義的跡象時,這段代碼都會列印“是”。代碼編譯成功,但是,在“你想要檢查回文主義的整數是什么”之后它不輸出任何內容for?:' 即使輸入像“12321”、“111”、“1234321”(回文)這樣的數字。
任何人都可以幫助我,如果可能的話,在不改變大部分代碼的情況下告訴我實作我想要的方法(證明回文主義)?
#include <cstring>
using namespace std;
bool isPalindrome(int x, string md) {
int y = md.length() 1;
char abz[y];
for (int i=0; i < md.length()-1; i) {
if (abz[i] == (md.length()-1)-i){
cout << "YES";
}
}
return true;
}
int main(){
int x;
cout << "What is the integer you wanna check palindromism for?: ";
cin >> x;
string md = to_string(x);
isPalindrome(x, md);
return 0;
}
謝謝!
uj5u.com熱心網友回復:
我不確定你想做什么isPalindrome。檢查大小字串是否len為回文的一種方法是比較其i第 -th 和(len-i-1)-th 字符的i范圍[0, len / 2)。如果它們在任何一點不同,則字串不是回文。
您可以這樣做:
bool isPalindrome(std::string const& md) {
if (md.empty()) // Empty strings are not palindrome
return false;
auto const len = md.size();
auto const halfLen = len / 2;
for (std::size_t i = 0; i != halfLen; i)
if (md[i] != md[len - i - 1])
return false;
return true;
}
任何人都可以幫助我,如果可能的話,在不改變大部分代碼的情況下告訴我實作我想要的方法(證明回文主義)?
請檢查我在代碼中添加的注釋:
// Include the correct headers
#include <iostream>
#include <string>
// Don't do this
//using namespace std;
// This just checks if the string is palindrome.
// It does not print anything.
bool isPalindrome(std::string const& md) {
if (md.empty())
return false;
auto const len = md.size();
auto const halfLen = len / 2;
for (std::size_t i = 0; i != halfLen; i)
if (md[i] != md[len - i - 1])
return false;
return true;
}
int main() {
// No need to parse the number and convert it to string again.
//int x;
std::string md;
std::cout << "What is the integer you wanna check palindromism for?: ";
// NOTE: you may input any string here: not just integers.
std::cin >> md;
std::cout << (isPalindrome(md) ? "YES" : "") << '\n';
// ^ print "YES" or nothing
return 0;
}
您還可以isPalindrome使用如下演算法和迭代器來實作:
// You'll need these two headers
#include <algorithm>
#include <iterator>
template <typename BidIt>
bool isPalindrome(BidIt first, BidIt last) {
if (first == last)
return false;
auto const halfLength = std::distance(first, last);
auto const mid = std::next(first, halfLength);
auto const rFirst = std::make_reverse_iterator(last);
return std::equal(first, mid, rFirst);
}
bool isPalindrome(std::string const& str) {
return isPalindrome(std::cbegin(str), std::cend(str));
}
這與上面的演算法基本相同,但您可以重用
template <typename BidIt>
bool isPalindrome(BidIt, BidIt);
有更多的容器,而不僅僅是std::string.
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/469098.html
