Sign in to follow this  
qwertyui

c prog doubt...

Recommended Posts


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[i]-'0');
mini = min(maxi,str[i]-'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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this