Find Largest number from set of given numbers ?

Answer : Find number of digits in the largest number. Let us assume number of digits be n…

Find Largest number from set of given numbers ?

  • Find number of digits in the largest number. Let us assume number of digits be n.
  • Create extended version of all numbers. In extended version, we have n+1 digit formed by concatenating the number of with itself and truncating extra digits.
  • Sorting the value from original numbers according to their extended values.
  • Concatenating to the sorted numbers produce the required result.

Sample Code in C++

[pastacode lang=”cpp” manual=”%2F%20Given%20an%20array%20of%20numbers%2C%20program%20to%20arrange%20the%20numbers%20to%20form%20the%20%0A%2F%2F%20largest%20number%20%0A%23include%20%3Ciostream%3E%20%0A%23include%20%3Cstring%3E%20%0A%23include%20%3Cvector%3E%20%0A%23include%20%3Calgorithm%3E%20%0Ausing%20namespace%20std%3B%20%0A%20%20%0A%2F%2F%20A%20comparison%20function%20which%20is%20used%20by%20sort()%20in%20printLargest()%20%0Aint%20myCompare(string%20X%2C%20string%20Y)%20%0A%7B%20%0A%20%20%20%20%2F%2F%20first%20append%20Y%20at%20the%20end%20of%20X%20%0A%20%20%20%20string%20XY%20%3D%20X.append(Y)%3B%20%0A%20%20%0A%20%20%20%20%2F%2F%20then%20append%20X%20at%20the%20end%20of%20Y%20%0A%20%20%20%20string%20YX%20%3D%20Y.append(X)%3B%20%0A%20%20%0A%20%20%20%20%2F%2F%20Now%20see%20which%20of%20the%20two%20formed%20numbers%20is%20greater%20%0A%20%20%20%20return%20XY.compare(YX)%20%3E%200%20%3F%201%3A%200%3B%20%0A%7D%20%0A%20%20%0A%2F%2F%20The%20main%20function%20that%20prints%20the%20arrangement%20with%20the%20largest%20value.%20%0A%2F%2F%20The%20function%20accepts%20a%20vector%20of%20strings%20%0Avoid%20printLargest(vector%3Cstring%3E%20arr)%20%0A%7B%20%0A%20%20%20%20sort(arr.begin()%2C%20arr.end()%2C%20myCompare)%3B%20%0A%20%20%0A%20%20%20%20for%20(int%20i%3D0%3B%20i%20%3C%20arr.size()%20%3B%20i%2B%2B%20)%20%0A%20%20%20%20%20%20%20%20cout%20%3C%3C%20arr%5Bi%5D%3B%20%0A%7D%20%0A%20%20%0A%2F%2F%20driver%20program%20to%20test%20above%20functions%20%0Aint%20main()%20%0A%7B%20%0A%20%20%20%20vector%3Cstring%3E%20arr%3B%20%0A%20%20%0A%20%20%20%20%2F%2Foutput%20should%20be%205545727825%20%0A%09arr.push_back(%2225%22)%3B%20%0A%09arr.push_back(%22457%22)%3B%20%0A%09arr.push_back(%22278%22)%3B%20%0A%09arr.push_back(%2255%22)%3B%20%0A%09printLargest(arr)%3B%20%0A%20%20%0A%20%20%0A%20%20%20return%200%3B%20%0A%7D%20″ message=”” highlight=”” provider=”manual”/]

Output

5545727825
Leave a Reply

Your email address will not be published. Required fields are marked *