「java出现最多的数字」java最大数字
本篇文章给大家谈谈java出现最多的数字,以及java最大数字对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。
本文目录一览:
JAVA求一个自然数中出现次数最多的数
import java.util.Hashtable;
public class Array {
public void getMaxnmber(long num){
String str=num+"";
Hashtable table=new Hashtable();
int len=0;
do{
len=str.length();
String s=str.substring(len-1);
str=str.substring(0,len-1);
if(table.containsKey(s)){
int i=(Integer)table.get(s);
table.put(s,i+1);
}else{
table.put(s, 0);
}
}while(len!=1);
int max=0,j=0;
for(int i=0;i9;i++){
if(table.get(i+"")!=null){
int number=(Integer)table.get(i+"");
if(number max){
max=number;
j=i;
}else if(number==max){
if(ij)
j=i;
}
}
}
System.out.println(j);
}
public static void main(String []arg){
Array arr=new Array();
arr.getMaxnmber(new Long(112233344));
}
}
java显示出现次数最多的数字
实现思路就是先把所有数字进行排序,之后根据排序结果计算出每个数出现的次数,之后取出次数最多的数即可。
public class Test {
public static void main(String[] args) {
int[] n = { 1, 1, 1, 1, 2, 22,2,2,2,2,2,2,2,2,2,2,2,2, 3, 4, 5, 6, 1, 1, 1,1,12, 1,1,1,13 ,0};
//设置中间数用来比较
int m = 0;
//排序,升序
Arrays.sort(n);
//保存结果map,n的元素为key,出现次数为value
Map nums = new HashMap();
//首先中间数出现次数为0
nums.put(m, 0);
//循环,当某个数已经在map里时,将次数加一
for (int i = 0; i n.length; i++) {
if (m == n[i]) {
int v = (Integer) nums.get(m);
v++;
nums.put(m, v);
} else {
nums.put(n[i], 1);
}
m = n[i];
}
//遍历得到最多次数的数
Iterator iterator = nums.keySet().iterator();
int maxNumber = 0;
int maxValue = 0;
while(iterator.hasNext()){
int key = (Integer)iterator.next();
int value = (Integer)nums.get(key);
if(valuemaxNumber){
maxNumber = value;
maxValue = key;
}
}
System.out.println("出现次数最多的数为:"+maxValue+",出现次数为:"+ maxNumber );
}
}
java如何找出一个int数组中出现次数最多
其实这个问题,涉及到两个过程
首先是统计数组中数字出现的次数,应该要有类似“数字 - 出现次数”这种结果出现,其实就是Map结构的key和value
然后就是找出出现次数最大的一个,并返回对应的数字即可
针对以上两个过程,推荐采用Java8的流(Stream)来处理,代码比较简单易懂,因此下面的示例代码,请在JDK8的环境下运行
int[] arr = {1, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5};
// 过程1 Collectors.groupingBy代表是分类,按照本身Function.identity()进行分类,那相同数字就会放在一起,Collectors.counting是统计相同数字的个数
MapInteger, Long map = IntStream.of(arr).boxed().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println("数字出现次数统计(数字=次数):" + map);
// 过程2 max方法是根据比较器(按照map的value进行排序)找出最大值
OptionalInteger maxOptional = map.entrySet().stream().max(Comparator.comparing(Map.Entry::getValue)).map(Map.Entry::getKey);
System.out.println("出现次数最多的数字:" + maxOptional.get());
最后结果如下
java出现最多的数字的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java最大数字、java出现最多的数字的信息别忘了在本站进行查找喔。
发布于:2022-12-08,除非注明,否则均为
原创文章,转载请注明出处。