--------------------------------------------------------------------------------------------------------------------------------------------------------
时间限制:1秒 空间限制:32768K 代码长度限制 100 KB
--------------------------------------------------------------------------------------------------------------------------------------------------------
题目描述
给定一个k位整数N = dk-1*10k-1 + ... + d1*101 + d0 (0<=di<=9, i=0,...,k-1, dk-1>0),请编写程序统计 每种不同的个位数字出现的次数。例如:给定N = 100311,则有2个0,3个1,和1个3。
输入描述:
每个输入包含1个测试用例,即一个不超过1000位的正整数N。
输出描述:
对N中每一种不同的个位数字,以D:M的格式在一行中输出该位数字D及其在N中出现的次数M。要求按D的升序输出。
输入例子:
100311
输出例子:
0:2 1:3 3:1
--------------------------------------------------------------------------------------------------------------------------------------------------------
实现思路:
(1).定义数字对象,包含数字及出现次数的属性;
(2).将输入的数字转换为字符数组,用map结构统计每个字符出现的次数;
(3).定义TreeSet集合,使用自定义排序器,根据字符升序排列,从map中将数据逐一实例化对象C并添加到set集合中,然后打印出即可。
--------------------------------------------------------------------------------------------------------------------------------------------------------
package com.biyao.algorithm.niuke.a1;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeSet;
public class Main_a1_011 {
public static void main(String[] args) {
class C{
Character c;
Integer times;
}
Comparator<C> myCompartor = new Comparator<C>(){
@Override
public int compare(C o1, C o2) {
if(o1 == null || o2 == null){
return -1;
}
int times1 = o1.c;
int times2 = o2.c;
if(times1 < times2){
return -1;
}else if(times1 == times2){
return 0;
}else{
return 1;
}
}
};
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
String numStr = scan.next();
Map<Character,Integer> timesMap = numAppearTimes(numStr);
TreeSet<C> cSet = new TreeSet<C>(myCompartor);
for (Character num : timesMap.keySet()) {
C c = new C();
c.c = num;
c.times = timesMap.get(num);
cSet.add(c);
}
for (C c : cSet) {
System.out.println(c.c + ":" + c.times);
}
}
}
public static Map<Character,Integer> numAppearTimes(String num){
Map<Character,Integer> timesMap = new HashMap<Character,Integer>();
char[] cArr = num.toCharArray();
for (int i = 0; i < cArr.length; i++) {
if(timesMap.containsKey(cArr[i])){
timesMap.put(cArr[i], timesMap.get(cArr[i])+1);
}else{
timesMap.put(cArr[i], 1);
}
}
return timesMap;
}
}