问题描述
小蓝对一个数的数位之和很感兴趣, 今天他要按照数位之和给数排序。当 两个数各个数位之和不同时, 将数位和较小的排在前面, 当数位之和相等时, 将数值小的排在前面。
例如, 2022 排在 409 前面, 因为 2022 的数位之和是 6, 小于 409 的数位 之和 13 。
又如, 6 排在 2022 前面, 因为它们的数位之和相同, 而 6 小于 2022 。
给定正整数 ,n,m, 请问对 1 到 n 采用这种方法排序时, 排在第 m 个的元 素是多少?
输入格式
输入第一行包含一个正整数 n 。
第二行包含一个正整数 m 。
输出格式
输出一行包含一个整数, 表示答案.
错误代码:
package Exerse;
import java.util.Scanner;
public class Count {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
char[] chs = new char[n];
int[] arr = new int[n];
int[] crr = new int[n];
//获得数位
for (int i = 0; i < n; i++) {
crr[i] = i + 1;
//转化为字符串,
String s = String.valueOf(i + 1);
//转化为字符数组
char[] chars = s.toCharArray();
int c = 0;
//数位相加
for (int j = 0; j < chars.length; j++) {
c = c + Integer.parseInt(String.valueOf(chars[j]));
}
arr[i] = c;
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length - 1; j++) {
if (arr[j] > arr[j + 1]) {
int tep = arr[j];
arr[j + 1] = arr[j];
arr[j] = tep;
System.out.println();
} else if (arr[j] == arr[j + 1]) {
if (crr[j] < crr[j + 1]) {
int tep = arr[j];
arr[j + 1] = arr[j];
arr[j] = tep;
System.out.println(crr[n]);
} else if (crr[j] > crr[j + 1]) {
int tep = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tep;
System.out.println(crr[n]);
}
}
}
}
}
}
正确代码:
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
//思路,map。
//key=数。 value=数的和
//按照和从小到大 如果value== 按照key的小到大
//利用tree map 制定规则 map存储
Scanner sc =new Scanner(System.in);
int n=sc.nextInt();
int k=sc.nextInt();
Map<Integer, Integer> map =new HashMap<>();
for(int i=1;i<=n;i++) {
int sum=he(i);
map.put(i, sum);
}
TreeMap<Integer, Integer> map1=new TreeMap<>(new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
if(map.get(o1)-map.get(o2)==0) {
//value相等 key从小到大
return o1-o2;
}
//否则按照 value值从小到大
return map.get(o1)-map.get(o2);
}
});
map1.putAll(map);
//要第k个Key
int cnt=1;
for(Integer a:map1.keySet()) {
if(cnt==k) {
System.out.println(a);
}
cnt++;
}
}
public static int he(int x) {
//返回一个数的数位和
int sum=0;
while(x>0) {
int c=x %10;
sum+=c;
x/=10;
}
return sum;
}
}
问题:
不知道,数位和相同的时候,比较值的时候,如何一一对应,这会导致代码错误
总结:
可以用集合的形式,刚好,对应一个键,一个值,也是一一对应,刚好解决了这种问题