Another approach:
Notice that you don't need the original values as numbers at all. In fact, since you need to use lexigraphical order to break ties (e.g., "13" < "4"), it's more convenient to consider the input as strings.
I'd create a class that stores the input as a string, and the sum of digits as a number. A constructor can compute the sum of digits of the string. Finally, add a less-than operator to compare as per the requirements:
1 2 3 4 5 6 7 8 9
|
class FunnyNum {
public:
FunnyNum(const std::string &str); // computes sumOfDigits
bool operator < (const FunnyNum &rightHandSide) const;
const std::string &getval() { return val; }
private:
std::string val;
unsigned sumOfDigits;
};
|
The advantage of this method over JLBorges's is that the sort will run faster since the sum of digits is pre-computed. The disadvantage is that it takes more space, again, because the sum of digits is pre-computed.
Once you have the class, you can dump the values into a vector<FunnyNum> and then use the standard sort() algorithm to sort them.
why is 4 in between 13 and 123? |
The sum of digits of 4, 13, and 123 are 4, 4, and 6 respectively. Since 4 and 13 tie, they are sorted lexographically (not numerically), so 13 < 4.
and where is 6?? it's in your example input so where's that gone? |
Maybe 6 tells how many numbers follow? It's not clear to me. Anyway, if 6 is part of the set of numbers, then I think the correct output is: