Chuyển đến nội dung chính

Tìm số nhỏ nhất lớn hơn có cùng số chữ số (C++, Java, Python)

Đề Bài: Cho một số n, tìm số nhỏ nhất có cùng tập hợp chữ số với n và lớn hơn n. Nếu n là số lớn nhất có cùng số chữ số, thì in ra “not possible”.

Ví dụ:

Input:  n = "218765"
Output: "251678"

Input:  n = "1234"
Output: "1243"

Input: n = "4321"
Output: "Not Possible"

Input: n = "534976"
Output: "536479"

Trích: Đề Thi HSG Thành Phố HCM 2008 – 2009

Lời Giải:

Sau đây là thuật toán:

  • Nếu tất cả các chữ số được sắp xếp theo thứ tự giảm dần, thì kết quả luôn là “Not possible”. Ví dụ: 4321.
  • Nếu tất cả các chữ số được sắp xếp theo thứ tự tăng dần, thì chúng ta cần hoán đổi hai chữ số cuối cùng. Ví dụ: 1234.
  • Đối với các trường hợp khác, chúng ta cần xử lý số nhỏ nhất bên phải
// C++ program to find the smallest number which greater than a given number 
// and has same set of digits as given number 
#include <iostream> 
#include <cstring> 
#include <algorithm> 
using namespace std; 

// Utility function to swap two digits 
void swap(char *a, char *b) 
{ 
   char temp = *a; 
   *a = *b; 
   *b = temp; 
} 

// Given a number as a char array number[], this function finds the 
// next greater number. It modifies the same array to store the result 
void findNext(char number[], int n) 
{ 
   int i, j; 

   // I) Start from the right most digit and find the first digit that is 
   // smaller than the digit next to it. 
   for (i = n-1; i > 0; i--) 
      if (number[i] > number[i-1]) 
      break; 

   // If no such digit is found, then all digits are in descending order 
   // means there cannot be a greater number with same set of digits 
   if (i==0) 
   { 
      cout << "Next number is not possible"; 
      return; 
   } 

   // II) Find the smallest digit on right side of (i-1)'th digit that is 
   // greater than number[i-1] 
   int x = number[i-1], smallest = i; 
   for (j = i+1; j < n; j++) 
      if (number[j] > x && number[j] < number[smallest]) 
         smallest = j; 

   // III) Swap the above found smallest digit with number[i-1] 
   swap(&number[smallest], &number[i-1]); 

   // IV) Sort the digits after (i-1) in ascending order 
   sort(number + i, number + n); 

   cout << "Next number with same set of digits is " << number; 

   return; 
} 

// Driver program to test above function 
int main() 
{ 
   char digits[] = "534976"; 
   int n = strlen(digits); 
   findNext(digits, n); 
   return 0; 
} 

 

// Java program to find next greater 
// number with same set of digits. 
import java.util.Arrays; 

public class nextGreater 
{ 
   // Utility function to swap two digit 
   static void swap(char ar[], int i, int j) 
   { 
      char temp = ar[i]; 
      ar[i] = ar[j]; 
      ar[j] = temp; 
   } 

   // Given a number as a char array number[], 
   // this function finds the next greater number. 
   // It modifies the same array to store the result 
   static void findNext(char ar[], int n) 
   { 
      int i; 
      
      // I) Start from the right most digit 
      // and find the first digit that is smaller 
      // than the digit next to it. 
      for (i = n - 1; i > 0; i--) 
      { 
         if (ar[i] > ar[i - 1]) { 
            break; 
         } 
      } 
      
      // If no such digit is found, then all 
      // digits are in descending order means 
      // there cannot be a greater number with 
      // same set of digits 
      if (i == 0) 
      { 
         System.out.println("Not possible"); 
      } 
      else
      { 
         int x = ar[i - 1], min = i; 
         
         // II) Find the smallest digit on right 
         // side of (i-1)'th digit that is greater 
         // than number[i-1] 
         for (int j = i + 1; j < n; j++) 
         { 
            if (ar[j] > x && ar[j] < ar[min]) 
            { 
               min = j; 
            } 
         } 

         // III) Swap the above found smallest 
         // digit with number[i-1] 
         swap(ar, i - 1, min); 

         // IV) Sort the digits after (i-1) 
         // in ascending order 
         Arrays.sort(ar, i, n); 
         System.out.print("Next number with same" + 
                           " set of digits is "); 
         for (i = 0; i < n; i++) 
            System.out.print(ar[i]); 
      } 
   } 

   public static void main(String[] args) 
   { 
      char digits[] = { '5','3','4','9','7','6' }; 
      int n = digits.length; 
      findNext(digits, n); 
   } 
} 
# Python program to find the smallest number which 
# is greater than a given no. has same set of 
# digits as given number 

# Given number as int array, this function finds the 
# greatest number and returns the number as integer 
def findNext(number,n): 
   
   # Start from the right most digit and find the first 
   # digit that is smaller than the digit next to it 
   for i in range(n-1,0,-1): 
      if number[i] > number[i-1]: 
         break
         
   # If no such digit found,then all numbers are in 
   # descending order, no greater number is possible 
   if i == 1 and number[i] <= number[i-1]: 
      print ("Next number not possible") 
      return
      
   # Find the smallest digit on the right side of 
   # (i-1)'th digit that is greater than number[i-1] 
   x = number[i-1] 
   smallest = i 
   for j in range(i+1,n): 
      if number[j] > x and number[j] < number[smallest]: 
         smallest = j 
      
   # Swapping the above found smallest digit with (i-1)'th 
   number[smallest],number[i-1] = number[i-1], number[smallest] 
   
   # X is the final number, in integer datatype 
   x = 0
   # Converting list upto i-1 into number 
   for j in range(i): 
      x = x * 10 + number[j] 
   
   # Sort the digits after i-1 in ascending order 
   number = sorted(number[i:]) 
   # converting the remaining sorted digits into number 
   for j in range(n-i): 
      x = x * 10 + number[j] 
   
   print ("Next number with set of digits is",x) 


# Driver Program to test above function 
digits = "534976"               

# converting into integer array, 
# number becomes [5,3,4,9,7,6] 
number = list(map(int ,digits)) 
findNext(number, len(digits)) 

# This code is contributed by Harshit Agrawal 

 

 

The post Tìm số nhỏ nhất lớn hơn có cùng số chữ số (C++, Java, Python) first appeared on Techacademy.



Nhận xét

Bài đăng phổ biến từ blog này

Đề Thi HSG Tin Học Lớp 12 Tỉnh Lào Cai Năm 2025

Rate this post Dưới đây là Đề Thi HSG Tin Học Lớp 12 Tỉnh Lào Cai Năm 2025 Bạn đọc có thể share lời giải bên dưới comment bài viết. Tham khảo: TỔNG HỢP ĐỀ THI CHUYÊN TIN TẤT CẢ CÁC TRƯỜNG TRÊN TOÀN QUỐC TỔNG HỢP ĐỀ THI HỌC SINH GIỎI TIN HỌC LỚP 9 TOÀN QUỐC TỔNG HỢP ĐỀ THI HỌC SINH GIỎI TIN HỌC LỚP 12 TOÀN QUỐC KHÓA HỌC LẬP TRÌNH C++ KHÓA HỌC LẬP TRÌNH PYTHON  The post Đề Thi HSG Tin Học Lớp 12 Tỉnh Lào Cai Năm 2025 first appeared on Techacademy .

Vẽ Tam Giác Trong C++

Vẽ tam giác trong C++ là một trong những bài tập lập trình về C++ sử dụng vòng lặp khá hay giúp các bạn luyện tư duy code cũng như cách sử dụng vòng lặp. Dưới đây là một số lời giải các bài tập vẽ tam giác trong C++ I. Vẽ Tam Giác Cân Trong C++ Viết chương trình C++ sử dụng ký tự * để vẽ tam giác vuông cân trong C++.Chúng ta sử dụng hai vòng lặp lồng nhau để giải bài toán này. Lời Giải: #include <stdio.h> #include <stdlib.h> int main() { int n; int q = 0; printf("Chuong trinh nay se in ra tam giac can\n"); printf("Nhap chieu cao tam giac cua ban: \n"); scanf("%d",&n); while (n > 0) { for (int i = 1; i<n; i++) printf("%c", ' '); for (int k = 0; k <= q; k ++) printf("%c", '*'); n -- ; q += 2 ; printf("\n"); } return 0; } II. Vẽ Hình Tam Giác Trong C++ Viết một chương trình in ra hình ...

Cách Vẽ Hình Trong Scratch

Hãy cùng Techacademy tìm hiểu cách vẽ hình trong lập trình Scratch nhé! Tại đây bạn sẽ biết thêm nhiều điều thú vị và hấp dẫn về cách vẽ các loại hình trong Scratch. I. Cách Vẽ Hình Vuông Trong Scratch Trong bài viết này mình sẽ hướng dẫn các bạn cách vẽ hình vuông trong Scratch đồng thời sử dụng kĩ thuật quay hợp lý để nhân bản tạo thành những hình vẽ đẹp đã ra trong các kì thi tin học trẻ phần vẽ hình bằng Scratch. Hãy tham khảo với onthihsg ngay nhé. + Thủ tục con vẽ hình vuông trong Scratch Trước hết ta cùng xây dựng một mảnh ghép để vẽ hình vuông với tham số là cạnh của hình vuông như sau: Cách Vẽ Hình Vuông Trong Scratch Chỉ cần một vòng lặp lại 4 lần việc vẽ một cạnh và xoay 90 độ là xong, quá đơn giản phải không nào + Vẽ các hình phức tạp hơn từ hình vuông Bây giờ ta hãy phát triển để vẽ hai hình trong đề thi tin học trẻ Đông Triều năm 2019 nào Cách Vẽ Hình Vuông Trong Scratch Nhìn hình ta thấy hình tạo thành từ 5 hình vuông vì vậy ta sẽ gọi 5 lần thủ tục vẽ h...