1117 数字之王


solution

  • 判断现有数字是否全为个位数
    • 全为个位数,找出出现次数最多的数字,并首行输出最多出现次数,第二行输出所有出现该次数的数值
    • 不全为个位数
      • 若当前位数值为0,无需处理
      • 若当前位数值非0,则每位立方相乘,并把结果个位和相加更新为当前位新数值
cpp 复制代码
#include<iostream>
using namespace std;
int n1, n2, flag[10] = {0}, a[1001], maxn = -1, judge = 0, first = 1, d;
int main(){
	scanf("%d%d", &n1, &n2);
	for(int i = n1; i <= n2; i++){
		a[i] = i;
	}
	if(n2 > 9) judge = 1;
	while(judge){
		judge = 0;
		for(int i = n1; i <= n2; i++){
			int t1 = 1, t2 = 0, t = a[i];
			if(t == 0) continue;
			while(t){
				d = t % 10;
				t /= 10;
				t1 *= d * d * d;
			}
			while(t1){
				d = t1 % 10;
				t1 /= 10;
				t2 += d;
			}
			a[i] = t2;
			if(t2 > 9) judge = 1;
		}
	}
	for(int i = n1; i <= n2; i++){
		flag[a[i]]++;
	}
	for(int i = 0; i < 10; i++){
		if(flag[i] > maxn) maxn = flag[i];
	}
	printf("%d\n", maxn);
	for(int i = 0; i < 10; i++){
		if(flag[i] == maxn){
			if(first) first = 0;
			else printf(" ");
			printf("%d", i);
		}
	}
	return 0;
} 

or

cpp 复制代码
#include<iostream>
using namespace std;
int n1, n2, flag[10] = {0}, a[1001], maxn = -1, judge = 0, first = 1, d;
int main(){
	scanf("%d%d", &n1, &n2);
	for(int i = n1; i <= n2; i++) a[i] = i;
	if(n2 > 9) judge = 1;
	while(judge){
		judge = 0;
		for(int i = n1; i <= n2; i++){
			int t1 = 1, t2 = 0, t = a[i];
			if(t == 0) continue;
			while(t){
				d = t % 10;
				t /= 10;
				t1 *= d * d * d;
			}
			while(t1){
				d = t1 % 10;
				t1 /= 10;
				t2 += d;
			}
			a[i] = t2;
			if(t2 > 9) judge = 1;
		}
	}
	for(int i = n1; i <= n2; i++){
		flag[a[i]]++;
		if(flag[a[i]] > maxn) maxn = flag[a[i]];
	}
	printf("%d\n", maxn);
	for(int i = 0; i < 10; i++){
		if(flag[i] == maxn){
			if(first) first = 0;
			else printf(" ");
			printf("%d", i);
		}
	}
	return 0;
} 
相关推荐
爱读书的小胖4 小时前
LeetCode 122:买卖股票的最佳时机 II(C)解题分析
算法
结局无敌4 小时前
React Native for OpenHarmony 实战:三方库 react-native-modal-dialog 的鸿蒙化适配指南
深度学习·算法·react native·react.js·harmonyos
OPEN-F4 小时前
ROS2系列教程:上位机建图与导航(原理综合)
算法·机器人
weixin_307779134 小时前
C++代码实现MATLAB中的fitrtree函数功能
开发语言·c++·算法·matlab
AI wins4 小时前
c++新增頭文件
c++
Shadow(⊙o⊙)4 小时前
仿muduo实现高并发服务器——事件就绪管理Channel.hpp
服务器·c++
爱读书的小胖4 小时前
Codewars:Rot13(C)解题分析
c语言·开发语言
tomwang03224 小时前
路径优化建模、优化算法分类及工程化小结
算法·数学建模·分类
小羊没烦恼!5 小时前
Ajax与JSON的一些总结
android·java·前端·数据库·mysql·算法·okhttp
by209995 小时前
哈希表——快速找到数据:冲突、删除与扩容的实现
数据结构·c++·哈希算法·散列表