Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

เขียนโปรแกรม C ตรวจสอบเลข Palindrome (อ่านจากหน้าหลังได้เหมือนกัน)

Palindrome คือ คำ ตัวเลข ประโยค หรือลำดับอักขระที่อ่านจากหน้าหลังหรือหลังหน้าได้เหมือนกัน เช่น 121, 12321, "level"

หลักการทำงาน

  1. รับตัวเลขจากผู้ใช้
  2. เก็บค่าเดิมไว้ในตัวแปร temp
  3. วนลูปกลับตัวเลขโดยใช้สูตร:
    while(n > 0) {
        r = n % 10;        // หาหลักสุดท้าย
        sum = (sum * 10) + r;  // สร้างตัวเลขกลับ
        n = n / 10;        // ตัดหลักสุดท้ายออก
    }
  4. เปรียบเทียบ temp กับ sum ถ้าเท่ากัน = Palindrome

ตัวอย่างโปรแกรม

#include <stdio.h>
#include <conio.h>

int main() {
    int n, r, sum = 0, temp;
    printf("Enter a number: ");
    scanf("%d", &n);
    temp = n;
    
    while(n > 0) {
        r = n % 10;
        sum = (sum * 10) + r;
        n = n / 10;
    }
    
    if(temp == sum)
        printf("It is a palindrome number!");
    else
        printf("It is not a palindrome number!");
    
    getch();
    return 0;
}

ผลลัพธ์

Enter a number: 12345
It is not a palindrome number

ตัวอย่างเพิ่มเติม

Enter a number: 12321
It is a palindrome number