使用 C++ 查詢第 N 個偶數長度迴文
如果您曾經使用過 C++,那麼您一定聽說過迴文數。因此,在本指南中,我們將使用適當的示例解釋有關“第 N 個偶數長度迴文”的所有內容。迴文數是指反轉後仍然相同的數字。不僅數字,而且單詞在字元反轉後拼寫保持不變。例如 -
數字 = {1,121,131,656,1221,1551}
單詞 = {saas,malayalam,level,mom}
它看起來很複雜,但在任何系統上都很容易執行。所以讓我們簡要討論一下回文。
第 N 個偶數長度迴文數
11、22、33、44、55、66、77、88、99、1001 等是一些偶數長度迴文數的示例。我們也可以將其定義為前半部分數字應等於後半部分數字。
如何查詢第 N 個偶數長度迴文數?
要查詢偶數長度的迴文數,我們需要將數字(由使用者給出)表示為兩部分。我們必須確保前半部分應等於後半部分,或者我們需要將數字與其反轉值連線起來。為了更好地理解,讓我們舉個例子
輸入 = 12
輸出 = 1221
解釋 - 12 不是迴文數,因此要將其轉換為迴文,將 12 與 21(12 的反轉)連線起來。我們可以透過給定的圖表來理解

讓我們在 C++ 中檢視相同的程式 -
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n; // Taking input from the user.
cout << n; // printing given number
while(n) // This while loop will print the number in rever
{
cout << n % 10; // Example n = 10. In first iteration n % 10 = 0,
n = n/ 10; // in second iteration n = 1, now our n % 10 = 1 so output
will be 01.
}
}在系統中執行上述函式後,您必須提供輸入以獲得輸出。因此,在此示例中,我們輸入了 3、56、10 並得到了輸出 33、5665、1001。
Input : 3 Output : 33 Input : 56 Output : 5665 Input : 10 Output : 1001
程式碼解釋
讓我們分部分理解程式碼
cin >> n; // Taking input from the user. cout << n; // printing given number
在這裡,我們從使用者那裡獲取輸入,首先按原樣列印數字,因為輸出的前半部分與輸入相同。
while(n) // This while loop will print the number in rever
{
cout << n % 10; // Example n = 10. In first iteration n % 10 = 0,
n = n/ 10; // in second iteration n = 1, now our n % 10 = 1 so output
will be 01.
}我們需要將前半部分與數字的反轉連線起來。在這個 while 迴圈中,我們使用模函式提取最後一個值並列印它,然後刪除該數字以移動到倒數第二個數字進行列印。透過這種方式,我們將給定數字表示為反轉。
結論
因此,在本文中,我們瞭解了迴文數和第 N 個偶數迴文數。我們已經解釋了查詢第 N 個偶數長度迴文數程式的完整資訊和方法。以上是理解迴文數的最簡單方法。因此,我們希望這能幫助您更準確地理解問題。
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP