剑指 Offer 43. 1~n 整数中 1 出现的次数
public int countDigitOne(int n) {
int digit = 1, res = 0;
int high = n / 10, cur = n % 10, low = 0;
while(high != 0 || cur != 0) {
if(cur == 0) res += high * digit;
else if(cur == 1) res += high * digit + low + 1;
else res += (high + 1) * digit;
low += cur * digit;
cur = high % 10;
high /= 10;
digit *= 10;
}
return res;
}
剑指 Offer 44. 数字序列中某一位的数字
class Solution {
public int findNthDigit(int n) {
int digit = 1;
long start = 1;
long count = 9;
while (n > count) { // 1.
n -= count;
digit += 1;
start *= 10;
count = digit * start * 9;
}
long num = start + (n - 1) / digit; // 2.
return Long.toString(num).charAt((n - 1) % digit) - '0'; // 3.
}
}
剑指 Offer 45. 把数组排成最小的数
- 初始化:字符串列表,保存格式
- 排序
- 返回:拼接所有字符串,并返回
采用快排
class Solution {
public String minNumber(int[] nums) {
String[] strs = new String[nums.length];
for(int i = 0;i<nums.length;i++){
strs[i]=String.valueOf(nums[i]);
}
quickSort(strs,0,strs.length-1);
StringBuilder res = new StringBuilder();
for(String s:strs)
res.append(s);
return res.toString();
}
public void quickSort(String[] strs, int l, int r) {
if(l >= r) return;
int i = l, j = r;
String tmp = strs[i];
while(i < j) {
while((strs[j] + strs[l]).compareTo(strs[l] + strs[j]) >= 0 && i < j) j--;
while((strs[i] + strs[l]).compareTo(strs[l] + strs[i]) <= 0 && i < j) i++;
tmp = strs[i];
strs[i] = strs[j];
strs[j] = tmp;
}
strs[i] = strs[l];
strs[l] = tmp;
quickSort(strs, l, i - 1);
quickSort(strs, i + 1, r);
}
}