Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Largest Number string sorting

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

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.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report