1、求从1 到 n 中1出现的次数。
public class Solution {
public int NumberOf1Between1AndN_Solution(int n) {
int count=0;
while(n>0){
String str=String.valueOf(n);
char [] chars=str.toCharArray();
for(int i=0;i<chars.length;i++){
if(chars[i]=='1')
count++;
}
n--;
}
return count;
}
}
2、输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Solution {
public String PrintMinNumber(int [] numbers) {
int n;
String s="";
ArrayList<Integer> list = new ArrayList<Integer>();
n=numbers.length;
for(int i=0; i<n; i++){
list.add(numbers[i]);
}
Collections.sort(list, new Comparator<Integer>(){
public int compare(Integer str1, Integer str2){
String s1 = str1+""+str2;
String s2 = str2+""+str1;
return s1.compareTo(s2);
}
});
for(int j: list){
s+=j;
}
return s;
}
}

本文介绍了两种实用的算法:一是计算从1到n中数字1出现的总次数,通过字符串转换和遍历的方法实现;二是对整数数组进行特殊排序,通过自定义比较器将数组元素拼接形成可能的最小数。

被折叠的 条评论
为什么被折叠?



