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

นับจำนวนเลข N หลักที่ num + Rev(num) = 10^N - 1 ด้วย C++

ได้รับจำนวน N เป็นอินพุต เป้าหมายคือหาจำนวนเลข N หลักทั้งหมดที่มีผลรวม num + rev(num) = 10N - 1

ตัวอย่าง

Input

N=4

Output

Count of all N digit numbers such that num + Rev(num) = 10N - 1 are: 90

Explanation

The numbers would be: 1. 1188 + 8811 = 9999 2. 2277 + 7722 = 9999 3. 1278 + 8721 = 9999 ...total 90 numbers

Input

N=5

Output

Count of all N digit numbers such that num + Rev(num) = 10^N - 1 are: 0

Explanation

As N is odd, there will be no such number as the middle element will be added to itself and cannot have sum as 9. Ex. 148+841=989

วิธีการที่ใช้ในโปรแกรม

สำหรับเลข N หลักใดๆ ผลรวมกับเลขย้อนกลับจะเป็น 999... (N ตัว) ถ้าผลรวมของแต่ละคู่หลักในทั้งสองเลขเป็น 9 กรณี N คี่ หลักกลางจะบวกกับตัวเอง ไม่มีจำนวนเต็มคู่ใดที่บวกกันได้ 9 ดังนั้นคำตอบคือ 0 กรณี N คู่ คู่หลักที่ 1-N, 2-(N-1), 3-(N-2)... ต้องรวมกันได้ 9 คู่ที่เป็นไปได้คือ (1+8), (2+7), (3+6), (4+5), (5+4), (6+3), (7+2), (8+1), (9+0) คำตอบคือ 9 × 10N/2 - 1

  • รับจำนวนเต็ม N เป็นอินพุต
  • ฟังก์ชัน digit_numbers(int N) รับ N คืนค่าจำนวนเลข N หลักที่ num + Rev(num) = 10^N - 1
  • กำหนดจำนวนนับเริ่มต้นเป็น 0
  • ถ้า N คี่ (N%2 == 1) คืนค่า 0
  • มิฉะนั้น กำหนด count = 9 * pow(10, N/2 - 1)
  • คืนค่า count เป็นผลลัพธ์

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

#include <bits/stdc++.h>
using namespace std;

int digit_numbers(int N){
    int count = 0;
    if (N % 2 == 1){
        return 0;
    } else {
        count = 9 * pow(10, N/2 - 1);
    }
    return count;
}

int main(){
    int N = 4;
    cout << "Count of all N digit numbers such that num + Rev(num) = 10^N - 1 are: " << digit_numbers(N);
    return 0;
}

Output

หากรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้:

Count of all N digit numbers such that num + Rev(num) = 10^N - 1 are: 90