c prog doubt...
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
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'); }}
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;}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement