当前位置: 首页 > news >正文

PTA甲级1005:Spell It Right

错误代码:

#include<iostream>
#include<vector>
#include<unordered_map>
using namespace std;int main() {unordered_map<int, string> map = {{0, "zero"}, {1, "one"}, {2, "two"}, {3, "three"}, {4, "four"},{5, "five"}, {6, "six"}, {7, "seven"}, {8, "eight"}, {9, "nine"}};int num;cin >> num;int sum = 0;// Handle the case where num is 0if (num == 0) {sum = 0;}else {while (num > 0) {sum += num % 10;num /= 10;}}// Handle the case where sum is 0 (for input num = 0)if (sum == 0) {cout << map[0] << endl;return 0;}vector<int> v;while (sum > 0) {int r = sum % 10;v.push_back(r);sum /= 10;}int length = v.size();for (int i = length - 1; i >= 0; i--) {cout << map[v[i]];if (i != 0) {cout << " ";}}return 0;
}

数字越界

正确代码(用字符串处理):

#include<iostream>
#include<vector>
#include<unordered_map>
using namespace std;int main() {unordered_map<int, string> map = {{0, "zero"}, {1, "one"}, {2, "two"}, {3, "three"}, {4, "four"},{5, "five"}, {6, "six"}, {7, "seven"}, {8, "eight"}, {9, "nine"}};string num;cin >> num;int sum = 0;// Calculate the sum of digitsfor (char c : num) {sum += c - '0';}// If sum is zero, we handle it directlyif (sum == 0) {cout << map[0] << endl;return 0;}vector<int> digits;while (sum > 0) {digits.push_back(sum % 10);sum /= 10;}// Output the digits in Englishfor (int i = digits.size() - 1; i >= 0; i--) {cout << map[digits[i]];if (i != 0) {cout << " ";}}cout << endl;return 0;
}

http://www.lryc.cn/news/394327.html

相关文章:

  • Vue笔记11-Composition API的优势
  • rancher管理多个集群
  • 某大会的影响力正在扩大,吞噬了整个数据库世界!
  • PostgreSQL主从复制:打造高可用数据库架构的秘籍
  • Fast R-CNN(论文阅读)
  • 视觉语言模型:融合视觉与语言的未来
  • 【CSAPP】-linklab实验
  • UE C++ 多镜头设置缩放 平移
  • 代码随想录Day69(图论Part05)
  • 53-1 内网代理3 - Netsh端口转发(推荐)
  • 慧哥充电桩开源平台小程序、PC后、手机商户端历经2年的无数次迭代。
  • 四、(1)网络爬虫入门及准备工作(爬虫及数据可视化)
  • 2024华为OD机试真题-分月饼-(C++/Python)-C卷D卷-200分
  • Git 查看提交历史
  • 力扣双指针算法题目:快乐数
  • 【Tools】了解人工通用智能 (AGI):未来的智能体
  • 华媒舍:8种网站构建推广方法全揭密!
  • 【Scrapy】 深入了解 Scrapy 下载中间件的 process_exception 方法
  • DevEco Studio无法识别本地模拟器设备的解决方法
  • EN-SLAM:Implicit Event-RGBD Neural SLAM解读
  • 2407C++,从构生成协议文件
  • 遗传算法求解TSP
  • 鸿蒙开发:Universal Keystore Kit(密钥管理服务)【明文导入密钥(C/C++)】
  • 视频汇聚/安防监控/GB28181国标EasyCVR视频综合管理平台出现串流的原因排查及解决
  • TypeError: Cannot read properties of null (reading ‘nextSibling‘)
  • 解决 npm intasll 安装报错 Error: EPERM: operation not permitted
  • redis实用技能
  • AcWing 1260:二叉树输出
  • 刷爆leetcode第十期
  • Python28-7.5 降维算法之t-分布邻域嵌入t-SNE