[leetcode] Largest Number
2015-06-20 15:09
302 查看
From : https://leetcode.com/problems/largest-number/
Given a list of non negative integers, arrange them such that they form the largest number.
For example, given
Note: The result may be very large, so you need to return a string instead of an integer.
Given a list of non negative integers, arrange them such that they form the largest number.
For example, given
[3, 30, 34, 5, 9], the largest formed number is
9534330.
Note: The result may be very large, so you need to return a string instead of an integer.
class Solution { public: static int comp(int a, int b) { string sa = to_string(a); string sb = to_string(b); return sa+sb > sb+sa; } string largestNumber(vector<int>& nums) { if(nums.size() == 0) return ""; sort(nums.begin(), nums.end(), comp); string ans = ""; for(int i=0, l=nums.size(); i<l; i++) { ans += to_string(nums[i]); } if(ans[0] == '0') return "0"; return ans; } };
public class Solution { public String largestNumber(int[] nums) { if (nums == null || nums.length == 0) { return ""; } String[] strs = new String[nums.length]; for (int i = 0; i < nums.length; ++i) { strs[i] = String.valueOf(nums[i]); } Arrays.sort(strs, new Comparator<String>() { public int compare(String a, String b) { return (b + a).compareTo(a + b); } }); if(strs[0].equals("0")) { return "0"; } StringBuilder sb = new StringBuilder(); for (String s : strs) { sb.append(s); } return sb.toString(); } }
相关文章推荐
- 分金币 Uva 11300
- Andriod开发环境搭建
- linux命令
- swift学习 一 基础部分 (上)
- android 中ListView 的优化
- 流程控制《2》switch
- linux命令
- [POJ 1330] Nearest Common Ancestors (倍增法)
- Convolutional Neural Networks for Visual Recognition 3
- OpenGL导入三维模型
- 流程控制《1》if
- 软件工程师需要数学的真正理由
- 帝国ECMS6.5灵动标签汇集
- POJ 1067 && HDU 1527 取石子游戏(博弈论)
- 杭电1302 The Snail
- 我是十娘沉梦江,遍洒芳汀,东流少语,喜欲狂,刹时惊梦,空一场!
- ListView已到底部和顶部的判断
- javascript基本包装类型
- 又是整数划分(poj1032)
- 记一次网站服务器搬迁实录