LeetCode刷题实战179:最大数
Given a list of non-negative integers nums, arrange them such that they form the largest number.
Note: The result may be very large, so you need to return a string instead of an integer.
题意
示例
示例 1:
输入:nums = [10,2]
输出:"210"
示例 2:
输入:nums = [3,30,34,5,9]
输出:"9534330"
示例 3:
输入:nums = [1]
输出:"1"
示例 4:
输入:nums = [10]
输出:"10"
解题
class Solution {
public String largestNumber(int[] nums) {
for(int i = 0; i < nums.length; i++){
for(int j = 0; j < nums.length - i - 1; j++){
String s1 = nums[j] + "" + nums[j + 1];
String s2 = nums[j + 1] + "" + nums[j];
if(s1.compareTo(s2) < 0){
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
}
}
}
String res = "";
for(int i = 0; i < nums.length; i++){
res += nums[i];
}
if(res.charAt(0) == '0'){
return "0";
}
return res;
}
}