Jump to content
  • Advertisement
Sign in to follow this  
qwertyui

c prog doubt...

This topic is 5039 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

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
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!