博客
关于我
算法——179、最大数(力扣)
阅读量:659 次
发布时间:2019-03-14

本文共 1380 字,大约阅读时间需要 4 分钟。

在解决这个问题时,我们需要将所有的数字组合在一起,然后通过字符串拼接的方式进行比较,最终得到一个最大的数字。这种方法可以利用字符串的便利性来处理不定长的数字问题。

我们可以通过以下步骤来实现这一目标:

  • 为每个数字创建字符串表示:

    • 遍历数字列表,将每个数字转换为字符串形式,这样可以便于后续的比较和拼接操作。
  • 比较字符串拼接的结果:

    • 对于每两个字符串,比较它们的两种拼接顺序(AB 和 BA),选择较大的顺序添加到结果中。
  • 优化字符串的顺序:

    • 因此字符串连接起来形成最大的数。
  • 具体实现代码如下:

    #include 
    #include
    #include
    using namespace std;string largestNumber(vector
    & nums) { vector
    tar; for (size_t i = 0; i < nums.size(); ++i) { string target; int num = nums[i]; if (num == 0) { tar.push_back("0"); continue; } int k = 1; while (k <= num) { k *= 10; } int power = 1; while (power <= num) { power *= 10; } power /= 10; while (power > 0) { target += ('0' + (num % power)); num /= power; power /= 10; } tar.push_back(target); } for (size_t i = 0; i < tar.size() - 1; ++i) { for (size_t j = i + 1; j < tar.size(); ++j) { if (tar[i] + tar[j] < tar[j] + tar[i]) { swap(tar[i], tar[j]); } } } if (tar.empty()) { return "0"; } string result; for (const auto& s : tar) { result += s; } return result;}

    这个方法通过比较每两个字符串拼接的结果,选择最大的顺序,最终得到最大的数字拼接结果。这样,我们就可以将所有的数字有效地组合起来,得到一个最大的数值。

    转载地址:http://tfeoz.baihongyu.com/

    你可能感兴趣的文章
    python | ply,一个无敌的 词法和语法分析工具 的Python 库!
    查看>>
    python | py2exe,一个超酷的 Python 库!
    查看>>
    python | pyautogui,一个超酷的 Python 库!
    查看>>
    python | pybaobabdt,一个超强的 决策树可视化 Python 库!
    查看>>
    python | pycco,一个神奇的 Python 库!
    查看>>
    python | pyg2plot,一个有趣的 数据可视化 Python 库!
    查看>>
    python | pymc,一个超强的 Python 库!
    查看>>
    python | pynsist,一个强大的 Python 库!
    查看>>
    python | pyparsing,一个强大的 Python 库!
    查看>>
    python | pyqtgraph,一个神奇的 Python 库!
    查看>>
    python读取文本文件数据
    查看>>
    python | Python mock对象与测试替身
    查看>>
    python | Python pandas实现数据追加和合并的最佳方法
    查看>>
    python | Python 中检查一个数字是否是三态数
    查看>>
    python | Python 蒙特卡洛模拟
    查看>>
    python | python-docx,一个超厉害的 Python 库!
    查看>>
    python | Python中使用@property装饰器
    查看>>
    python | Python中的functools模块高级应用
    查看>>
    python | Python中的itertools模块使用技巧
    查看>>
    python | Python中的事件驱动编程模型
    查看>>