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

Sequential Digits หาตัวเลขที่หลักเรียงติดกันในช่วงใน C++

ตัวเลขมี sequential digits ถ้าหลักแต่ละหลักมากกว่าหลักก่อนหน้า 1 หาตัวเลขทุกตัวใน [low, high] ที่มีคุณสมบัตินี้ เรียงจากน้อยไปมาก

ตัวอย่าง: low=100, high=300 → [123, 234]

วิธีแก้ปัญหา (Generate All Sequential Numbers)

สร้างทุกตัวเลขที่เป็นไปได้ (มีเพียง 45 ตัวสำหรับ 1-9 digits):

  1. วนความยาว i = 1 ถึง 9
  2. วนเริ่มต้น j = 1 ถึง 9-i+1
  3. สร้างตัวเลข: x = 0; วน k=0 ถึง i-1: x = x×10 + (j+k)
  4. ถ้า low ≤ x ≤ high → ใส่ในคำตอบ

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

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

void print_vector(vector<int> v) {
    cout << "[";
    for (int i = 0; i < v.size(); i++) cout << v[i] << ", ";
    cout << "]" << endl;
}

class Solution {
public:
    vector<int> sequentialDigits(int low, int high) {
        vector<int> ans;
        for (int i = 1; i <= 9; i++) {
            for (int j = 1; j + i - 1 <= 9; j++) {
                int x = 0;
                for (int k = 0; k < i; k++) x = x * 10 + (j + k);
                if (low <= x && x <= high) ans.push_back(x);
            }
        }
        return ans;
    }
};

int main() {
    Solution ob;
    print_vector(ob.sequentialDigits(500, 5000));
    return 0;
}

Input

500 5000

Output

[567, 678, 789, 1234, 2345, 3456, 4567, ]