Get the App
SLTechnology News&Howtos  ›  Development  › 

Example Analysis of Largest Number string sorting

Shulou Source: shulou.com Published: 2022-06-02 10:51:40 10月01日 Update

This article shows you an example analysis of Largest Number string sorting, which is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

Main idea of the topic:

Give a set of numbers and let the strings of these numbers form the largest number, which can be very large, expressed as a string.

Train of thought:

Using bubble sorting, sort numeric strings, and then concatenate them.

Compare two numeric strings to determine which is larger by comparing the size of s1+s2 and s2+s1.

The code is as follows:

Class Solution {public: string largestNumber (vector& nums) {vector numstr; for (int I = 0; I)

< nums.size(); i++) { stringstream ss; ss 0) //strcmp((numstr[j] + numstr[j + 1]).data(), (numstr[j + 1] + numstr[j]).data()) { tmp = numstr[j]; numstr[j] = numstr[j+1]; numstr[j + 1] = tmp; tmp.clear(); } } } string result; for (int i = numstr.size() - 1; i >

= 0;-- I) {/ / extreme case, the maximum number is 0, then directly return "0" if (numstr [numstr.size ()-1] = = "0") return "0"; result + = numstr [I];} numstr.clear () Return result;}}

The code is as follows:

Class Solution {public: string largestNumber (vector & num) {vector arr; for (auto i:num) arr.push_back (to_string (I)); sort (begin (arr), end (arr), [] (string & S1, string & S2) {return s1+s2 > S2;}); string res; for (auto s:arr) res+=s While (res [0] = ='0' & & res.length () > 1) res.erase (0prime1); return res;}}

The third parameter of sort uses the lambda expression, which is an extension of Clippers 11.

The above is an example analysis of Largest Number string sorting. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Tags: Characters strings numbers sorting examples analysis maximum code content skills knowledge large concise concise three two parameters size gist that is Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Shulou Tech Info Docker MySQL vpn