zoukankan      html  css  js  c++  java
  • LeetCode——Largest Number

    Description:

    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.

    把所给的数字排列成最大的数,首先想到的思路是按位比较,但是那样比较麻烦而且容易出BUG,所以还有一种简单的思路就是在排序的时候比较两种情况前后排列取结果最大的那种顺序。代码少好理解。

    public class Solution { 
        public String largestNumber(int[] nums) {
           ArrayList<Number> list = new ArrayList<Number>();
           for(int i : nums) {
               list.add(new Number(i+""));
           }
           Collections.sort(list);
           StringBuilder sb = new StringBuilder();
           for(int i=list.size()-1; i>=0; i--) {
               sb.append(list.get(i).val);
           }
           java.math.BigInteger b = new java.math.BigInteger(sb.toString());
           return b.toString();
        }
    }
    class Number implements Comparable<Number> {
        String val;
        public Number(String val) {
            this.val = val;
        }
        public int compareTo(Number n) {
            java.math.BigInteger a = new java.math.BigInteger(this.val + n.val);
            java.math.BigInteger b = new java.math.BigInteger(n.val + this.val);
            return a.compareTo(b);
        }
    }
    
  • 相关阅读:
    cookie和session会话技术
    hdoj 1176 免费馅饼
    nyoj 14 会场安排问题
    hdoj 1575 Tr A
    poj 1163 The Triangle
    hdoj 2157 How many ways??
    贪心Poj1328
    贪心 序列
    差分约束Poj 3169 Layout
    差分约束Poj3159 Candies
  • 原文地址:https://www.cnblogs.com/wxisme/p/4601330.html
Copyright © 2011-2022 走看看