1.Description:
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).
Notes:
-
Each input file contains one test case. Each case contains a pair of integers a and b where −. The numbers are separated by a space.
-
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
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:
之前第一次做的时候分正负号讨论过,所以代码不算简洁,然后参考有些大神的,写了一个较为简洁的!继续加油!
笨鸟先飞,水滴石穿!