Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ตรวจสอบว่าตัวเลขเป็น Palindrome ใน C++ . หรือไม่


ที่นี่เราจะดูวิธีการตรวจสอบว่าตัวเลขเป็นพาลินโดรมหรือไม่ ตัวเลขพาลินโดรมเหมือนกันทั้งสองทิศทาง ตัวอย่างเช่น ตัวเลข 12321 คือ palindrome แต่ 12345 ไม่ใช่ palindrome

ตรรกะตรงไปตรงมามาก เราต้องกลับตัวเลขนั้น และหากจำนวนกลับกันเท่ากับจำนวนจริง แสดงว่าเป็นพาลินโดรม ไม่เช่นนั้นก็ไม่ใช่ ให้เราดูอัลกอริธึมเพื่อความเข้าใจที่ดีขึ้น

อัลกอริทึม

isPalindrome(n) −

อินพุต − หมายเลข n

ผลผลิต − จริง หากตัวเลขเป็นพาลินโดรม มิฉะนั้น เท็จ

begin
   temp := n
   rev := 0
   while n > 0, do
      rev := rev * 10 + (n mod 10)
      n := n / 10
   done
   if rev = temp, then
      return true
   return false
end

ตัวอย่าง

#include <iostream>
using namespace std;
bool isPalindrome(int number) {
   int temp = number;
   int rev = 0;
   while(number > 0){
      rev = 10 * rev + number % 10; //take the last digit, and attach with the rev number /= 10;
   }
   if(rev == temp)
      return true;
   return false;
}
int main() {
   int n = 12321;
   if(isPalindrome(n)){
      cout << n << " is palindrome number";
   } else {
      cout << n << " is not a palindrome number";
   }
}

ผลลัพธ์

12321 is palindrome number