168. Excel表列名称
public class Solution168 { public String convertToTitle(int n) { String restult = ""; while(n>0) { n--; restult =(char)('A'+(n%26))+restult; n=n/26; } return restult; } public static void main(String[] args) { // TODO Auto-generated method stub Solution168 s = new Solution168(); System.err.println(s.convertToTitle(26)); System.err.println(s.convertToTitle(52)); System.err.println(s.convertToTitle(27)); System.err.println(s.convertToTitle(26)); System.err.println(s.convertToTitle(28)); System.err.println(s.convertToTitle(701)); } }
204. 计数质数
public class Solution204 { public int countPrimes(int n) { int result = 0; for (int i = 1; i < n; i++) { if (isPrime(i)) { result++; } } return result; } /** * AKS算法计算一个数是否是素数 * https://stackoverflow.com/questions/1801391/what-is-the-best-algorithm-for-checking-if-a-number-is-prime * @param n * @return */ public boolean isPrime(int n) { if (n == 1) { return false; } if (n == 2 || n == 3) { return true; } if (n % 2 == 0 || n % 3 == 0) { return false; } int i = 5, w = 2; while (i * i <= n) { if (n % i == 0) { return false; } i += w; w = 6 - w; } return true; } public static void main(String[] args) { // TODO Auto-generated method stub Solution204 s = new Solution204(); System.out.println(s.countPrimes(10)); } }
179. 最大数
import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class Solution179 { public String largestNumber(int[] nums) { List<String> lists =new ArrayList<String>(nums.length); for(int num:nums) { lists.add(num+""); } lists.sort(new Comparator<String>() { @Override public int compare(String o1, String o2) { // TODO Auto-generated method stub return (o2+o1).compareTo(o1+o2); } }); if(lists.get(0).equals("0")) { return "0"; } StringBuffer sb = new StringBuffer(); for(String numStr:lists) { sb.append(numStr); } return sb.toString(); } public static void main(String[] args) { // TODO Auto-generated method stub Solution179 s = new Solution179(); int[] nums = new int[] {3,30,34,5,9}; System.out.println(s.largestNumber(nums)); } }
这道题先思考清楚本质是一个排序问题,坑的地方在于0的处理上。