题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805528788582400

思路

问题1,插入逗号时,i从1开始
问题2,长度为3的倍数时,最后一个不可以插入
问题3,长度为4时,因为我解决问题2的方法,会导致少插入一个逗号,因此加入了一个特判

算法笔记上解决的方法也很巧妙,采用一边判断一边print的方法可以把我的问题都规避

  1. for(int k = len - 1; k >= 0; k++)
  2. {
  3. printf("%d",num[k]);
  4. if(k>0&&k%3==0)printf(",");
  5. }

代码

  1. #include<iostream>
  2. #include<string>
  3. #include<algorithm>
  4. using namespace std;
  5. int main(){
  6. int a, b, count = 0;
  7. string ans;
  8. cin>>a>>b;
  9. int c = a + b;
  10. if(c<0) cout << '-';
  11. c = abs(c);
  12. do{
  13. ans.push_back(c%10+'0');
  14. c = c/10;
  15. }while(c!=0);
  16. for(int i = 1; i < ans.length()-1;i++)
  17. {
  18. if(ans.length() == 4)
  19. {
  20. ans.insert(3,",");
  21. break;
  22. }
  23. if(i%3==0)
  24. {
  25. ans.insert(i+count,",");
  26. count++;
  27. }
  28. }
  29. reverse(ans.begin(),ans.end());
  30. cout<<ans;
  31. }