zoukankan      html  css  js  c++  java
  • PAT-1001 A+B Format 解答(C/C++/Java/python)

    1.Description:

     

    2.Example:

    Input:
    -100000 9
    Output:
    -999,991

    3.Solutions:

    C Version:

    //
    // Created by SheepCore on 2020-02-23.
    //
    
    #include <stdio.h>
    #include <string.h>
    
    int main() {
        int a, b; 
        char str[10];
    
        scanf("%d %d", &a, &b);
        sprintf(str, "%d", a + b);
        int len = strlen(str);
        for (int i = 0; i < len; ++i) {
            printf("%c", str[i]);
            if(str[i] == '-')
                continue;
            if((i + 1) % 3 == len % 3 && i != len -1)
                printf(",");
        }
    } 

    Result:

    C ++ Version:

    #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<< ",";
        }
    }

    Result:

    Java Version:

    package pat_online_test;
    
    import java.util.Scanner;
    
    /**
     * @author sheepcore
     */
    public class P1001_add_format {
        public static void main(String[] args) {
            int a, b, sum;
            String s;
            Scanner scanner = new Scanner(System.in);
    
            a = scanner.nextInt();
            b = scanner.nextInt();
            sum = a + b;
            boolean sign = sum >= 0;
            s = sum + "";
            int len = s.length();
    
            for (int i = 0; i < len; i++) {
                System.out.print(s.charAt(i));
                if(s.charAt(i) == '-'){
                    continue;
                }
                if((i+1) % 3 == len % 3 && i != len -1){
                    System.out.print(',');
                }
            }
        }
    }

    Result:

     Python Version:

    """
     A+B Format
     Created by SheepCore at 2020-3-24
    """
    
    line = input().split()
    a, b = eval(line[0]), eval(line[1])
    sum = a + b
    
    sign = sum >= 0
    str = str(sum)
    length = len(str)
    
    i = 0
    while i < len(str):
        print(str[i], end='')
        if str[i] == '-':
            i += 1
            continue
        if (i+1) % 3 == length % 3 and i != length - 1:
            print(',', end='')
        i += 1

    Result:

    4.Summary:

    字符打印时,注意下标的转换。

    之前第一次做的时候分正负号讨论过,所以代码不算简洁,然后参考有些大神的,写了一个较为简洁的!继续加油!

    笨鸟先飞,水滴石穿!

  • 相关阅读:
    18.10.29 考试总结
    【BZOJ】2730: [HNOI2012]矿场搭建
    BZOJ [ZJOI2007]仓库建设
    18.10.24 考试总结
    ZOJ 3740 Water Level
    洛谷 P2474 [SCOI2008]天平
    洛谷 P4180 【模板】严格次小生成树[BJWC2010]
    CF961E Tufurama
    18.10.22 考试总结
    18.10.19 考试总结
  • 原文地址:https://www.cnblogs.com/sheepcore/p/12359660.html
Copyright © 2011-2022 走看看