• Advertisement
Sign in to follow this  

c prog doubt...

This topic is 4824 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, How can I make a program in c/c++ that takes a number and finds the max and min digit in the number? Thanks

Share this post


Link to post
Share on other sites
Advertisement

void findminmax(unsigned int x,int& maxi,int& mini)
{
char str[32];
sprintf(str,"%d",x);
maxi = 0;
mini = 9;
for(int i=0;i<strlen(str);i++)
{
maxi = max(maxi,str-'0');
mini = min(maxi,str-'0');
}
}

Share this post


Link to post
Share on other sites
I think it's a fair bit cleaner to do the arithmetic yourself, than to convert back and forth from the ASCII digit range using old C-style hacks (char buffer, sprintf(), strlen):


std::pair<int, int> digitRange(int x) {
// Return value is a pair<min, max>.
std::pair<int, int> limits(9, 0);
int lastDigit;
if (x < 0) x *= -1; // Not sure of div/mod behaviour on negative numbers in C++...
while(x) {
lastDigit = x % 10; x /= 10;
if (lastDigit < limits.first) limits.first = lastDigit;
if (lastDigit > limits.second) limits.second = lastDigit;
}
return limits;
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement