Table of Contents
Algorithm
Approach 1: - Naïve Approach
Example
Output
Method 2: Efficient method
结论
Home Backend Development C++ The largest number not exceeding N and not containing any number in S

The largest number not exceeding N and not containing any number in S

Sep 05, 2023 pm 05:17 PM
number maximum Does not exceed

The largest number not exceeding N and not containing any number in S

The challenge of finding the largest number not exceeding a given number N and not containing any of the digits in a string S is a problem that involves string manipulation and number theory. The goal is to determine the greatest possible number that is less than or equal to N while also excluding all of the digits found in the string S.

For example, consider a scenario where N equals 1000 and S equals "42". In this case, the largest number that does not exceed N and does not contain any digits in S is 999. This is because 999 is the largest possible number formed using the digits 0, 1, 3, 5, 6, 7, 8 and 9, excluding the digits 4 and 2 in the string S.

Different approaches can be used to solve this problem, such as iterating through all numbers up to N and verifying if their digits are not present in S, or by utilizing more complex methods like dynamic programming or backtracking.

Algorithm

Step 1 − We will declare two string variables named ‘N’ and ‘S’ in the main() function.

Step 2 - We will pass these two variables as parameters to the LargestNumberFinder() function.

Step 3 − We will convert the string number N and S into integer implicitly to do mathematical operations such as comparison.

Step 4 - We will remove the leading 0's from the numbers stored in N either manually or by creating a function that will do the same thing every time.

Step 5 − Then, we will start comparing the digits of the both the strings and finding out which is the largest number formed not more than 'N' that doesn't contain any digit from string ' S'.

Approach 1: - Naïve Approach

The basic way to find the largest number in a given string using all the numbers in another string is as follows. The main function declares variables and calls the LargestNumberFinder function. This function takes two strings as input and checks every value less than N that has all the digits in string S. If the condition is met, the value is returned in string format. The attendance function is used to determine whether the value stored in 'i' is part of a string S while converting S to an integer data type. The input string is converted to an integer and a loop is used to evaluate the condition. The code outputs the maximum value of all numbers in a given string that is also present in another string.

Example

is translated as:

Example

This code is a solution that finds the largest number smaller than N (the input string converted to an integer) consisting of the digits in the string S. The code utilizes two functions, 'attendance' and 'LargestNumberFinder' to determine and return the largest number. The attendance function takes as input an integer 'i' and a string 's', checks if the value stored in 'i' is part of the string 's', and converts 's' to an integer data type. The LargestNumberFinder function takes two strings 'x' and 's' as input, converts 'x' to an integer, and then uses the attendance function to check all values ​​less than N and all numbers are in 's'. The main function declares the variable and calls the LargestNumberFinder function, which returns the largest number as a string.

#include <iostream>
#include <string>
#include <vector>

// function to check whether value stored in ‘i’ is part of string S while also converting S into integer data type.
bool attendance(int i, std::string s) {
   while (i) {
      int first_digit = i % 10;
      i /= 10;
      int t = std::stoi(s);
      bool found = false;
      while (t) {
         int second_digit = t % 10;
         t /= 10;
         if (second_digit == first_digit) {
            found = true;
            break;
         }
      }
      if (!found)
         return false;
   }
   return true;
}

// function to input two strings and check for each value less than N with all digits present in S.
std::string LargestNumberFinder(std::string x, std::string s) {
   int N = std::stoi(x);
   for (int i = N; i >= 1; i--) {
      if (attendance(i, s)) {
         return std::to_string(i);
      }
   }
   return "-1";
}

// main function to declare the variables and call the function.
int main() {
   std::string N = "100709";
   std::string S = "70";
   std::cout << LargestNumberFinder(N, S);
}
Copy after login

Output

77777
Copy after login

Method 2: Efficient method

For the solution to problem 2, which is to get the largest possible number by replacing the numbers of the given number string N with the numbers of the given string S, this is an efficient method. The method first checks if every number of N is present in S and replaces the first number found in S with the largest number in S that is not in N. The remaining numbers are then replaced with the largest number in S that is not in N. Leading zeros are then removed and the result is returned as the largest possible number. This method is more efficient than the previous method because it does not require the string to be sorted.

Example

is translated as:

Example

The code solves a problem of finding the greatest number that can be formed from a given string "N" by replacing a digit with the highest digit not present in the string "S". The code utilizes an efficient method to solve the problem. The LargestNumberFinder function takes two string inputs, "num" and "s", and returns the largest possible number. The vector "vis_s" is utilized to store the values ​​of string "s". The code first identifies the first digit of string "num" that is part of string "s". Then it swaps that digit with the highest digit not present in string "s". The code then finds the highest digit not found in string "s" and replaces the rest of the digits in string "num" with that digit. The leading zeros are removed from the final string, and if the string is empty, the function returns "0". The code outputs the result by calling the function with inputs "N" and " S".

#include <iostream>
#include <string>
#include <vector>

using namespace std;

// function to check for all values of String N with String S and replacing the digit if found same with the largest possible digit not present in S.
string LargestNumberFinder(string num, string s) {
   vector<bool> vis_s(10, false);
   for (int i = 0; i < (int)s.size(); i++) {
      vis_s[int(s[i]) - 48] = true;
   }
   int n = num.size();
   int in = -1;
   for (int i = 0; i < n; i++) {
      if (vis_s[(int)num[i] - '0']) {
         in = i;
         break;
      }
   }
   if (in == -1) {
      return num;
   }
   for (char dig = num[in]; dig >= '0'; dig--) {
      if (vis_s[(int)dig - '0'] == 0) {
         num[in] = dig;
         break;
      }
   }
   char LargestDig = '0';
   for (char dig = '9'; dig >= '0'; dig--) {
      if (vis_s[dig - '0'] == false) {
         LargestDig = dig;
         break;
      }
   }
   for (int i = in + 1; i < n; i++) {
      num[i] = LargestDig;
   }
   int Count = 0;
   for (int i = 0; i < n; i++) {
      if (num[i] == '0')
         Count++;
      else
         break;
   }
   num.erase(0, Count);
   if ((int)num.size() == 0)
      return "0";
   return num;
}
int main() {
   string N = "161516";
   string S = "756";
   cout << LargestNumberFinder(N, S);
   return 0;
}
Copy after login

Output

149999
Copy after login

结论

通过这篇文章,我们更接近理解这些问题背后的原因,并理解了这些概念,这些概念将帮助我们在之前提到的重大实际问题中使用这些基本概念。就像在我们的代码中,我们分别解决每个问题,然后像制作美丽的手工品一样将代码缝合在一起,同样,我们将使用这个概念,尝试逐个解决问题。我们通常会从朴素的方法开始,但通过敏锐的眼光和努力,我们会找到更高效的方法。谁知道在阅读完这篇文章后,你会找到更好、更高效的方法,并进一步简化解决方案。所以,让我们坚持我们的信念和对思维和编码的信任,同时告别。

The above is the detailed content of The largest number not exceeding N and not containing any number in S. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

iOS 17: How to change iPhone clock style in standby mode iOS 17: How to change iPhone clock style in standby mode Sep 10, 2023 pm 09:21 PM

Standby is a lock screen mode that activates when the iPhone is plugged into the charger and oriented in horizontal (or landscape) orientation. It consists of three different screens, one of which is displayed full screen time. Read on to learn how to change the style of your clock. StandBy's third screen displays times and dates in various themes that you can swipe vertically. Some themes also display additional information, such as temperature or next alarm. If you hold down any clock, you can switch between different themes, including Digital, Analog, World, Solar, and Floating. Float displays the time in large bubble numbers in customizable colors, Solar has a more standard font with a sun flare design in different colors, and World displays the world by highlighting

Generate random numbers and strings in JavaScript Generate random numbers and strings in JavaScript Sep 02, 2023 am 08:57 AM

The ability to generate random numbers or alphanumeric strings comes in handy in many situations. You can use it to spawn enemies or food at different locations in the game. You can also use it to suggest random passwords to users or create filenames to save files. I wrote a tutorial on how to generate random alphanumeric strings in PHP. I said at the beginning of this post that few events are truly random, and the same applies to random number or string generation. In this tutorial, I'll show you how to generate a pseudo-random alphanumeric string in JavaScript. Generating Random Numbers in JavaScript Let’s start by generating random numbers. The first method that comes to mind is Math.random(), which returns a float

C++ program to round a number to n decimal places C++ program to round a number to n decimal places Sep 12, 2023 pm 05:13 PM

Representing numbers as output is an interesting and important task when writing a program in any language. For integer types (data of type short, long, or medium), it is easy to represent numbers as output. For floating point numbers (float or double type), sometimes we need to round them to a specific number of decimal places. For example, if we want to represent 52.24568 as three decimal places, some preprocessing is required. In this article, we will introduce several techniques to represent floating point numbers to a specific number of decimal places by rounding. Among the different approaches, it is important to use a C-like format string, use the precision argument, and use the round() function from the math library. Let’s look at them one by one. with

Use C++ to write code to find the Nth non-square number Use C++ to write code to find the Nth non-square number Aug 30, 2023 pm 10:41 PM

We all know numbers that are not the square of any number, such as 2, 3, 5, 7, 8, etc. There are N non-square numbers, and it is impossible to know every number. So, in this article, we will explain everything about squareless or non-square numbers and ways to find the Nth non-square number in C++. Nth non-square number If a number is the square of an integer, then the number is called a perfect square. Some examples of perfect square numbers are -1issquareof14issquareof29issquareof316issquareof425issquareof5 If a number is not the square of any integer, then the number is called non-square. For example, the first 15 non-square numbers are -2,3,5,6,

Check if it is a number using is_numeric() function in PHP Check if it is a number using is_numeric() function in PHP Jun 27, 2023 pm 05:00 PM

In the PHP programming language, the is_numeric() function is a very commonly used function, used to determine whether a variable or value is a number. In actual programming, it is often necessary to verify the value entered by the user to determine whether it is a numeric type. In this case, the is_numeric() function can be used to determine. 1. Introduction to is_numeric() function The is_numeric() function is a function used to detect whether a variable or value is a number. Returns tru if the variable or value is a number

Find numbers that are not divisible by any number in a range, using C++ Find numbers that are not divisible by any number in a range, using C++ Sep 13, 2023 pm 09:21 PM

In this article, we will discuss the problem of finding numbers between 1 and n (given) that are not divisible by any number between 2 and 10. Let us understand this with some examples - Input:num=14Output:3Explanation:Therearethreenumbers,1,11,and13,whicharenotdivisible.Input:num=21Output:5Explanation:Therearefivenumbers1,11,13,17,and19,whicharenotdivisible. Solved Simple method if

Numbers in Java (with 0 prefix and strings) Numbers in Java (with 0 prefix and strings) Aug 29, 2023 pm 01:45 PM

Numbers in Java It is important to understand that the number class is not a tangible class but an abstract class. Inside it, we have a set of wrapper classes that define its functionality. These wrapper classes include Integer, Byte, Double, Short, Float, and Long. You may notice that these are the same basic data types we discussed earlier, but they are represented as separate classes with uppercase names to conform to the class naming convention. The compiler automatically converts primitive data types to objects and vice versa as required for a particular function or program scope, and numeric classes are part of the java.lang package. This process is called autoboxing and unboxing. By grasping the abstract nature of numeric classes and their corresponding wrapper classes, we can

Java program to check if a number is divisible by 5 Java program to check if a number is divisible by 5 Sep 13, 2023 pm 09:01 PM

In mathematics, the divisibility rule of 5 states that if a number ends in 0 or 5, it is divisible by 5. There is another way to determine the divisibility rule of 5, if the remainder is 0, then return the number divisible by 5. The mod(%) operator is commonly used in programming for integer division. Let's give an example. The given number is 525, the number ends with 5 and is divisible by 5. The given number is 7050 which ends with 0 and is divisible by 5. The given number is 678 which does not end with 0 and 5 and is not divisible by 5. In this article, we will solve the question of whether the number is divisible by 5. Algorithm The following steps are where we will use the java.util.* packages to get user input of primitive data types. from main class

See all articles