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

โปรแกรม C++ พิมพ์พาลินโดรมทั้งหมดในช่วงที่กำหนด


ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมที่พิมพ์พาลินโดรมทั้งหมดในช่วงที่กำหนด

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

ตัวอย่างโค้ด C++

#include <iostream>
using namespace std;

// checking if the number is a palindrome
int is_palin(int n){
    int rev = 0;
    for (int i = n; i > 0; i /= 10)
        rev = rev*10 + i%10;
    return (n==rev);
}

void countPal(int min, int max){
    for (int i = min; i <= max; i++)
        if (is_palin(i))
            cout << i << " ";
}

int main(){
    countPal(99, 250);
    return 0;
}

ผลลัพธ์

99 101 111 121 131 141 151 161 171 181 191 202 212 222 232 242