今年參加了兩次華為OD機試,遺憾都沒通過。在這里把機試的題目分享給大家,希望大家一同進步。華為機試題目描述比較復雜,意思大概如下
題目:
給出一個陣列,里面的每個數字都不超過5位,請拼接處最大值。陣列長度最大為25。求拼接后的最大值
public class MaximumNumber {
/*
給定一個陣列:組合成最大數值
*/
public String combinate(int[] nums) {
if (null == nums || nums.length == 0) {
return "";
}
StringBuilder stringBuilder = new StringBuilder();
compareNums(nums);
for (int i = 0; i < nums.length; i++) {
stringBuilder.append(String.valueOf(nums[i]));
}
return stringBuilder.toString();
}
/*
排序
*/
private void compareNums(int[] nums) {
if (null == nums) {
throw new NullPointerException();
}
if (nums.length == 1) {
return;
}
int temp;
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (compare(nums[i], nums[j])) {
temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
}
}
/*
比較兩個數字哪個作高位排列
example: 9, 98 --> 998; 15, 18 --> 1815
*/
private boolean compare(int a, int b) {
String aa = String.valueOf(a);
String bb = String.valueOf(b);
int ab = Integer.valueOf(aa + bb);
int ba = Integer.valueOf(bb + aa);
if (ba > ab) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
MaximumNumber maximumNumber = new MaximumNumber();
int[] b = {35, 11, 23, 4, 34};
System.out.println(maximumNumber.combinate(b));
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/169827.html
標籤:Java相關
上一篇:JAVA
