码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • 【PAT甲级】1001 A+B Format


    【PAT题解集合】

    1001 A+B Format

    题目详情 - 1001 A+B Format (pintia.cn)

    Calculate a+b and output the sum in standard format – that is, the digits must be separated into groups of three by commas (unless there are less than four digits).

    Input Specification:

    Each input file contains one test case. Each case contains a pair of integers a and b where −106≤a,b≤106. The numbers are separated by a space.

    Output Specification:

    For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.

    Sample Input:

    -1000000 9
    
    • 1

    Sample Output:

    -999,991
    
    • 1

    思路

    1. 先将 a+b 的结果转换成字符串,方便处理,这里用到的库函数是 to_string(sum) ,它可以将数字 sum 转换成字符串。
    2. 在得到的字符串 x 中,从后往前进行遍历,每次遍历都将 x[i] 加入到答案字符串数组 res 中。注意是 res = x[i] + res ,因为是从后往前遍历,所以每次加入的数字要放在 res 左边。
    3. 通过对 j 取余来判断当前是否已经遍历了 3 个数字,除此之外还要注意遍历到第一个数字的情况,如果已经遍历到第一个数字,即使已经遍历了 3 个数字也不能加逗号。

    代码

    #include
    using namespace std;
    
    int main()
    {
        int a, b;
        cin >> a >> b;
        
        //进行字符串转化
        string x = to_string(a + b);
        
        //从后往前遍历
        string res = "";
        for (int i = x.size() - 1, j = 0; i >= 0; i--)
        {
            j++;
            res = x[i] + res;
            //每遍历三个数字加一个逗号,但是要排除作为第一个数字的情况
            if (j % 3 == 0 && i && x[i - 1] != '-')  res = "," + res;
        }
        cout << res << endl;
        
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
  • 相关阅读:
    Kotlin的关键字 lateinit 和 lazy
    常用SQL总结
    Tushare上的数据为什么会缺失呢?
    大数据安全标准化产生得背景
    程序员兼职那些事儿
    程序员级别分析,看看你是哪个级别
    前端面试之前端工程化篇
    .NET Equal、==、ReferenceEqual
    lammps已跑完,不想重跑,如何补充新的计算?
    MySQL要不要容器化?能不能运行在Docker?
  • 原文地址:https://blog.csdn.net/Newin2020/article/details/126276446
  • 最新文章
  • 攻防演习之三天拿下官网站群
    数据安全治理学习——前期安全规划和安全管理体系建设
    企业安全 | 企业内一次钓鱼演练准备过程
    内网渗透测试 | Kerberos协议及其部分攻击手法
    0day的产生 | 不懂代码的"代码审计"
    安装scrcpy-client模块av模块异常,环境问题解决方案
    leetcode hot100【LeetCode 279. 完全平方数】java实现
    OpenWrt下安装Mosquitto
    AnatoMask论文汇总
    【AI日记】24.11.01 LangChain、openai api和github copilot
  • 热门文章
  • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
    奉劝各位学弟学妹们,该打造你的技术影响力了!
    五年了,我在 CSDN 的两个一百万。
    Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
    面试官都震惊,你这网络基础可以啊!
    你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
    心情不好的时候,用 Python 画棵樱花树送给自己吧
    通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
    13 万字 C 语言从入门到精通保姆级教程2021 年版
    10行代码集2000张美女图,Python爬虫120例,再上征途
Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1
正则表达式工具 cron表达式工具 密码生成工具

京公网安备 11010502049817号