第一题 从 1 到 n 整数中 1 出现的次数
最直观的想法,求1到n中每个整数中1出现的次数,然后相加即可。而求每个十进制整数中1出现的次数,我们先判断这个数的个位数是否是1,如果这个数大于10,除以10之后再判断个位数是否为1,循环直至求出该整数包含1的个数
public class NumberOf1Between1AndN {
public int NumberOf1Between1AndN_Solution(int n) {
int count = 0;
for (int i = 1; i <= n; i++) {
count += getNumOf1(i);
}
return count;
}
private int getNumOf1(int i) {
int count = 0;
while (i > 0) {
if (i % 10 == 1) {
count++;
}
i = i / 10;
}
return count;
}
}
不直观的算法 参考 https://blog.csdn.net/yi_afly/article/details/52012593 没太理解,今天再想想
若weight为0,则1出现次数为roundbase
若weight为1,则1出现次数为roundbase+former+1
若weight大于1,则1出现次数为rount*base+base
public static int count(int n) {
if(n<1) return 0;
int round = n;
int base =1;
int cnt=0;
while(round>0) {
int weight = round%10;
round/=10;
cnt+= cnt*base;
if(weight==1)
cnt+=(n%base)+1;
else if(weight>1)
cnt+=base;
base*=10;
}
return cnt;
}
第二题 数字序列中某一位的数字
题目没太懂 后边再说
第三题 把数组排成最小的数
方法就是讲整数变string,然后用arrays排序,排序完打印
public static String PrintMinNumber(int[] numbers) {
int n = numbers.length;
String[] nums = new String[n];
for (int i = 0; i < n; i++)
nums[i] = numbers[i] + "";
//lambda箭头来表示,还有这种方法,简洁
Arrays.sort(nums, (s1, s2) -> (s1 + s2).compareTo(s2 + s1));
String ret = "";
for (String str : nums)
ret += str;
return ret;
}
网友评论