zoukankan      html  css  js  c++  java
  • 1001. A+B Format (20)

     

    时间限制
    400 ms
    内存限制
    32000 kB
    代码长度限制
    16000 B
    判题程序
    Standard
    作者
    CHEN, Yue

    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

    Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.

    Output

    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.




    C++:

     1 #include <iostream>
     2 #include <string>
     3 #include <sstream>
     4 using namespace std;
     5 int main()
     6 {
     7 int n1,n2,sum;
     8  
     9 while(cin>>n1)
    10 {
    11   cin>>n2;
    12        sum=n1+n2;
    13   stringstream ss; string s;
    14   ss<<sum;
    15   ss>>s;
    16   int i;
    17   char ch[20];
    18   int len=0;int num=0;
    19  
    20        for(i=s.length()-1;i>=0;i--)
    21  {
    22         ch[len++]=s[i];
    23              num++;
    24 if(sum>=0&&num==3&&i!=0)   
    25 {
    26   ch[len++]=',';
    27   num=0;
    28 }
    29  if(sum<0&&num==3&&i!=0&&i!=1)   
    30 {
    31   ch[len++]=',';
    32   num=0;
    33 }
    34  }
    35  
    36  
    37         for(i=len-1;i>=0;i--)
    38 cout<<ch[i];
    39  
    40 cout<<endl;
    41  
    42 }
    43    return 0;
    44 }

     Python:

     1 a,b = raw_input().split( )
     2 a = int(a)
     3 b = int(b)
     4 c = a+b
     5 c = str(c)
     6 n = len(c) - 1 
     7 a = ""
     8 while n >= 0:
     9     for x in range(0,3):
    10         a = c[n] + a
    11         n-=1
    12         if n < 0:
    13             break
    14     if n > 0:
    15         a = ',' + a
    16     if n == 0 and c[0] != '-':
    17         a = ',' + a
    18 print a

    Java

     1 import java.util.*;
     2 
     3 public class Main {
     4     public static void main(String args[])
     5     {
     6         Scanner in = new Scanner(System.in);
     7         int a = in.nextInt();
     8         int b = in.nextInt();
     9         in.close();
    10         int c = a + b;
    11         String str = Integer.toString(c);
    12         for(int i = str.length() -3 ; i > 0 ; i = i -3)
    13         {
    14             if(!(i==1 && c < 0))
    15                 str = str.substring(0,i) + ',' + str.substring(i,str.length());
    16         }
    17         System.out.println(str);
    18     }
    19 }
  • 相关阅读:
    ACM解题之快速输出杨辉三角形(前68行)
    ACM解题之素矩阵
    ACM解题之回文序列
    python批量修改文件名
    HTML页面导航栏页脚不动,变换中间部分
    VS2013正则表达式应用示例
    <<数学传奇>>概述
    C#在不同平台下DLL的引用问题
    在C++中实现类似Java的“synchronized”
    VS编译完成后自动复制到远程机器
  • 原文地址:https://www.cnblogs.com/xiaoyesoso/p/4263589.html
Copyright © 2011-2022 走看看