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)

Sample Input:

-1000000 9
Sample Output:
-999,991

第一种方法,注意题目说明的数字范围,及时处理越界即可。
为啥捏,因为 int 是32位的,最大2的31次方。题目给的数据容易越界

第二种方法,使用to_string将A+B的值转化为字符串,按需要的格式进行修改。
string s = to_string(a + b);
to_string的用法推荐查阅官方文档,表述清晰

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);
Convert numerical value to string
Returns a string with the representation of val.

第二种方法较为简单清晰。

#include <iostream>
using namespace std;
int main() {
        int a, b;
        cin >> a >> b;
        string s = to_string(a + b);
        int len = s.length();
        for (int i = 0; i < len; i++) {
                cout << s[i];
                if (s[i] == '-')
                        continue;
                if ((i + 1) % 3 == len % 3 && i != len - 1)
                         cout << ",";
        }
        return 0;
}

最新文章

  1. git review出现的问题
  2. 关于iOS地图定位中点击设置-&gt;隐私-&gt;定位服务 闪退问题
  3. 我的复杂的OpenCV编译之路(OpenCV3.1.0 + VS2010 + Win7)
  4. BZOJ-1196 公路修建问题 最小生成树Kruskal+(二分??)
  5. Linux 基础网络设置
  6. hdu 1059 多重背包
  7. C# 控制连接超时
  8. linux远程连接mysql数据库
  9. Spring MVC 3.0.5+Spring 3.0.5+MyBatis3.0.4全注解实例详解(五)
  10. prototype对象的真正作用
  11. DevOps探索
  12. 知识点3-6:HTML辅助方法
  13. mybatis逆向工程生成代码
  14. C#-WinForm 串口通信
  15. python_爬百度百科词条
  16. mybatis 动态 SQL 官方文档
  17. JavaScript是如何工作: 深入探索WebSocket和HTTP/2与SSE + 如何选择正确的路径!
  18. Jenkins与网站代码上线解决方案【转】
  19. poj 1182 (关系并查集) 食物链
  20. 连续的if语句

热门文章

  1. Day3-T4
  2. mount(挂载)
  3. HDU——Monkey and Banana 动态规划
  4. Android进阶——Android视图工作机制之measure、layout、draw
  5. h5-transform二维变换-扑克牌小案例
  6. 随机森林RF
  7. 翻译——3_Gaussian Process Regression
  8. h5与安卓、ios交互
  9. JavaScript学习总结(八)
  10. ImageTag,图片左上侧有一个小标签