Write a Program That Find the Largest Integer in a String

C language: How to find the largest number created by digits from n using string

Your approach is correct: sorting the digits in decreasing order produces the largest number from these digits.

Your implementation is flawed:

  • you actually sort them in increasing order. You should change while (j >= 0 && s[j] > key) to

     while (j >= 0 && s[j] < key)
  • the null terminator is set at the wrong position: you clear the last character in s. If the line read from stdin ends with a newline, this may erase it, unless the user typed a TAB character, but if the input consists only of digits, the last one will be removed. Change the code to:

     s[l - 1] = '\0';

Here is an alternative using counting sort:

#include <stdio.h>

void max_number(char s[]) {
/* array to store the number of occurrences of each digit */
int count[10] = { 0 };
int i, d, c;
/* enumerate all characters from the string, stop at the null terminator */
for (i = 0; s[i]; i++) {
/* only count digits from '0' to '9' */
if (s[i] >= '0' && s[i] <= '9') {
/* increase the digit count for this digit */
count[s[i] - '0']++;
}
}
/* output the digits from highest to lowest */
for (i = 0, d = 10; d --> 0;) {
for (c = count[d]; c --> 0;)
s[i++] = '0' + d;
}
if (i == 0) {
/* there were no digits in the string: store a 0 */
s[i++] = '0';
}
if (s[0] == '0') {
/* there were only zeroes in the string: keep a single 0 */
i = 1;
}
/* set the null terminator */
s[i] = '\0';
printf("%s\n", s);
}

int main() {
char s[100];
if (fgets(s, sizeof(s), stdin))
max_number(s);
return 0;
}

How do I find the max integer of a string of integer without using a list?

The idea is to separate out the integers from the string (as you are already doing, but a bit wrongly), and keep track of the max so far. When a character is not digit, you convert the n_string to int and compare with max_ which keeps track of maximum int found so far, and then set n_string empty for next number.

The final checking is for the last number, since at the end of the string there may not always be a non-digit, so the last iteration will not be in the else part.

def max_numbers(s):
n_string = ''
max_ = 0
for char in s:
if char.isdigit():
n_string += char
else:
if n_string and int(n_string) > max_:
max_ = int(n_string)
n_string = ''

if n_string and int(n_string) > max_:
max_ = int(n_string)

return max_

print(max_numbers('22 53 123 54 243'))

Output:

243

Edit:

If n_string is empty, int(n_string) fails with an error

ValueError: invalid literal for int() with base 10: ' '

So in order to avoid that, a check to see if n_string is empty or not is required before doing int(n_string). In python, empty string evaluates to False, and non-empty string to True. So, simply writing

if n_string and int(n_string) > max_:

checks if n_string is non-empty and n_string as integer is greater than max_. When n_string is empty, the second part of the if is not evaluated due to short-circuiting behaviour of if, thus the error is avoided.


Some related links:

  • Short-circuit in boolean expressions in python: Link
  • Truth value testing in python: official docs and an answer by me

How do I determine the largest value number in a String?

In the following example, the maxIndex variable will contain the index of the highest value in the array and the actual position will be maxIndex + 1, which is what you are looking for.

String test = "0, 1, 3, 2, 2, 1, 1, 4, 2, 5, 1, 1, 0, 1, 241";
String[] testArray = test.split(", ");

int max = Integer.MIN_VALUE, maxIndex = 0;

for (int i = 0; i < testArray.length; i++) {
if (Integer.parseInt(testArray[i]) > max) {
max = Integer.parseInt(testArray[i]);
maxIndex = i;
}
}

Edit: initialized the other variables, and corrected some code thanks to comments

Gathering Largest and Smallest Numbers in C-String C++

The final result of small is \0, since you' ve scanned the null character, And its value is smallest.

See this: https://ideone.com/6sLWJV

And, as a suggestion. If you guarantee that your input won't surpass the size of the array, stop iteration by judging whether the current character is \0, rather than calculating the iteration time and compare it with the size of array.

How to find the largest and smallest possible number from an input integer?

I believe what you are trying to achieve is to input some number, and then reorder it's digits to achieve a maximum and minimum value:

int num[100];
scanf("%[^\n]", num);

First of all I would recommend either setting scanf() to parse the input to an integer:

int number;
scanf("%d", &number);

Or using an string (array of chars) to hold your digits one by one. (I'm going to continue this way).

//Initialize all elements to '\0', in order to know where the user input ended.
char digits[100] = {'\0'};
scanf("%99[^\n]", digits);

/*Simply using scanf("%99s", digits) should work too.
No need to protect from the new line since we aren't doing any other calls to scanf().*/

Note on scanf(): As hinted in the comments to this answer, you may get a string overflow if you do not specify the maximum width of your string; instead of scanf("%[^\n]", digits), consider scanf("%99[^\n], digits). The width specifier should be the size of the length of your buffer minus one. (We need to make it one byte shorter so scanf() can add the string terminator (null character) at the end of our buffer, had we used all the space in it). You may also want to check if scanf() was successful by checking the return value:

/* We only have one string in our arguments, so scanf() should return 1.
If anything goes wrong, terminate the program*/
int numOfAssignments = scanf("%99[^\n]", digits);
if (numOfAssignments != 1) return 1;
// return numOfAssignments; may also be a good idea.

Consider using fgets() instead, except you would have to manually remove the new line character.

========= End of Note =========

Let's make a define for the max number of digits, since we will be using it on most of the code: #define MAX_SIZE 100

Then, since you need to print the initial number at the end of the program, you were trying to copy it to a variable:

original = num;

Problem here is, that int num[100] (now char digits[100]) is an array, and you were just copying it's address to original. To copy the whole number the user had given the program you would need to copy each element of the array, one by one (or we could use memcpy() instead):

for (i = 0; i < MAX_SIZE && i != '\0'; ++i){
original[i] = digits[i];
}

I will actually use the digits array as my "original number" and will declare two extra arrays maxDigits[MAX_SIZE] and minDigits[MAX_SIZE] to hold the digits in ascending (min) and descending (max) order. Next, I will initialize either of the arrays:

minDigits[MAX_SIZE] = { '\0' };
maxDigits[MAX_SIZE] = { '\0' };

//Stop copying values when the null character is found, also count the number of digits.
while (digits[count] != '\0') {
maxDigits[count] = digits[count++];
}

Now, since this is supposed to hold the digits in descending order, we have to sort the array (this could probably have been done in the previous step, but this is about all the brainpower I have at 1:00 AM).

//Look up Insertion Sort to learn about this sorting algorithm
int buffer;
for (i = 1; i < count; ++i) {
buffer = maxDigits[i];
j = i - 1;
while (j >= 0 && maxDigits[j] < buffer) {
maxDigits[j + 1] = maxDigits[j];
j = j - 1;
}
maxDigits[j + 1] = buffer;
}

Now that maxDigits is sorted we need to sort minDigits.
This one should be easy, since all we need is to flip maxDigits:

for (i = 0; i < count; ++i) {
minDigits[i] = maxDigits[count - i - 1];
}

Of course, we need to calculate the difference between the maximum and minimum value of reordered digits, so we should convert maxDigits and minDigits to integers in order to do math with them:

/*This will multiply each digit with it's position value and add it together
(hundreds + tens + ones...)*/
int multiplier = 1;
for (i = count - 1; i >= 0; --i, multiplier *= 10) {
max += (maxDigits[i] - '0') * multiplier;
min += (minDigits[i] - '0') * multiplier;
}
/*Since the digits we stored are actually characters from '0' to '9' and not
integers 0 to 9, we need to substract the value of '0' or else our min and max values will be off.*/

Finally, we just have to output the results:

printf("The difference between largest(%d) and smallest(%d) of the integer %s is %d.\n", max, min, digits, max - min);

Text file contains strings and numbers. How do I find the largest number associated with the string?

Ok take a integer variable and initialize with 0 or smallest integer (if file has negative integer) then take another variable string

So what you want to do now is parse line by line and if number is greater than your integer variable put the corresponding string in the string variable; when you r done with the file you will have biggest integer and its corresponding string.



Related Topics



Leave a reply



Submit