Jump to content
  • Advertisement
Sign in to follow this  
qwertyui

c prog doubt...

This topic is 5123 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.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!