PAT Grade 1001 A + B Format 20 minutes

Topic Introduction

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).

Enter information

Each input file contains one test case. Each case contains a pair of integers a and b where ​​ -10^6 <= a,b <= 10^6 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.

SAMPLE INPUT

-1000000 9

Sample Output

-999,991

analysis

Given two numbers, a and B, and their calculated and added every three separators (add separators thousandth)
as are within the scope of the int, so we do not consider the problem of overflow. (Maximum 2 × 10 ^ 6)

First, there is a simple way is pulled inside a very useful Java classes --DecimalFormat
(PS:. PAT test in which, for a time limit of 20 minutes less demanding subject, often in Java can spike quickly as long as good String, BigInteger, DecimalFormat and other categories)

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.StringTokenizer;

public class Main {
	static final int BUFFER_SIZE = 8192 * 25;
	static BufferedReader br;
	static StringTokenizer tokenizer;

	static void initInput(InputStream in) throws Exception {
		br = new BufferedReader(new InputStreamReader(in), BUFFER_SIZE);
		tokenizer = new StringTokenizer("");
	}

	static String next() throws Exception {
		while (!tokenizer.hasMoreTokens()) {
			tokenizer = new StringTokenizer(br.readLine());
		}
		return tokenizer.nextToken();
	}

	static int nextInt() throws Exception {
		return Integer.parseInt(next());
	}

	static PrintWriter pw;

	public static void main(String[] args) throws Exception {
		initInput(System.in);
		pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out), BUFFER_SIZE));
		
		/*正式代码开始*/
		int a = nextInt(),b=nextInt();
		int c = a+b;
		DecimalFormat df = new DecimalFormat("#,###");
		//如果要求按四位分割,就改为#,####即可
		pw.println(df.format(c));
		/*结束*/
		
		pw.flush();
	}
}

As shown, the core code is only four lines. (On why the IO to be so attached to write the text, and will give a template)
Here Insert Picture Description
Not surprisingly, time-consuming and memory are high, it is written in Java PAT normal (Python strong time-consuming than Java. but without prejudice nice too ~ on the line)

Normal test we ran one minute to get points, but as a learning phase should then seriously think about how to do it in the end.
For a number 1234567890 (after summation), it is represented as 1,234,567,890
If this number is converted to a string, each character a correspondence between subscripts as follows:
0. 5. 4. 3. 1 2. 6. 7. 8. 9
. 1 2. 4. 3 567 890
As can be seen, in the print str [0], str [3 ], after str [6] need to print a comma character.
By observing laws, set at index I , the condition is satisfied (i + 1)% 3 == len% 3 need to print a comma. If i was the last (ie i == len-1 ) you do not need to print. If it is negative, you can skip, also in line with the law.
Such as: -1234567
0 2. 3. 1. 4. 5. 6. 7

  • 3 1,2 4,5 67
    prints a comma after str [1], str [4 ].
    (Reference @ Liu recalcitrant idea)
    C ++ to achieve the following:
#include <iostream>
#include <string>
using namespace std;
int main() {
	int a, b;
	scanf("%d %d", &a, &b);
	string s = to_string(a + b);
	for (int i = 0; i < s.length(); i++) {
		printf("%c", s[i]);
		if (s[i] != '-' && (i + 1) % 3 == s.length() % 3 && i != s.length() - 1)
			printf(",");
	}
	return 0;
}

Here Insert Picture Description
(This is time-consuming bad days to do the ...)

Appendix - (problems running time) on PAT exam efficiency

Three to four questions beginning I was using Java answer, but the back part of the topic really can not pass. (300ms limit the following topics, by using Java almost impossible), the following tips for Java, is only improved to a certain extent, if you just learn to practice your own topics, you can use Java to write, but if you want to take the exam Please switch as early as possible. The reason is that:
1, by Pat official explanation , Oh, that's all.
2, PTA judgments related questions system Java compiler has been a long time no maintenance, start-up time Java virtual machine are also counted in the program run time.
First, if the answer Java
Java belonging to explain after the first compiled language, although .java into .class files compiled by the time do not count, but the Java virtual machine starts (up to 50ms +) of the time will be counted inside. If the IO inefficient method, the effect will be even worse. In contrast, pure interpreted languages (such as Python), and have actually faster (comparison).
The following are several methods to enhance the speed, the actual effect is in turn weakened.

  • Rewritten in C ++.
  • Scanner reads stop using, instead of the package through the Reader class
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)));

Scanner While easy to use, but the efficiency is poor, see
Fast Input for Java
experiments using a Java dozen international players do acm

  • Instead of using StringTokenizer String.parse, StringTokenizer efficiency will be several times higher than String.parse.
  • On one of the links where there are explanations.
  • System.in output stop using, instead of the package through the Writer class.
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));

Use BufferedWriter transformed from the System.out encapsulation, efficiency can be improved, reuse PrintWriter packaging, easy to use print, printf, println like.

  • All static objects can try static (doubtful)
    this practice is GC does not check the origin and static objects recovered in the domain, and reduce the frequency of GC is to some extent increase (in fact, the effect of operating efficiency is very obvious, almost no)
    will not timely object is set to null it also might be able to improve efficiency
  • Modify BufferedReader, BufferedWriter default buffer size (default is 8192, I will increase it to 25 times the original), so as to change the memory read efficiency.
    This is also why write one line:
static final int BUFFER_SIZE = 8192 * 25;

Forget is seen where someone once so written, the actual effect is doubt, may not use eggs.

Java can be drawn fully on the inside a few of the most efficient template read as follows:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class Main{
	static final int BUFFER_SIZE = 8192*25;
	static BufferedReader br;
	static StringTokenizer tokenizer;

	static void initInput(InputStream in) throws Exception {
		br = new BufferedReader(new InputStreamReader(in), BUFFER_SIZE);
		tokenizer = new StringTokenizer("");
	}
	static String next() throws Exception{
		while(!tokenizer.hasMoreTokens()) {
			tokenizer = new StringTokenizer(br.readLine());
		}
		return tokenizer.nextToken();
	}

	static int nextInt() throws Exception {
		return Integer.parseInt(next());
	}
	static double nextDouble() throws Exception{
		return Double.parseDouble(next());
	}
	static PrintWriter pw;
	public static void main(String[] args) throws Exception {
		initInput(System.in);
		pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out),BUFFER_SIZE));
		
		/*在这里插入你的代码*/
		int i = nextInt(); //读取一个整数
		String s = next(); //读取一个字符串
		double d = nextDouble(); //读取一个浮点数
		pw.flush();
	}
}

NOTE: StringTokenizer default delimiter is a space and line feed, if necessary after using the method spilt other means, or with next () reads the appropriate string.
Second, if the answer C language
switch C ++, can not live without substantially STL.
3. If the answer using C ++
C ++ is nothing to say, in general, no big problem (often, Java requires the use of optimization algorithms can too, C ++ or even violence on the line)
only a few points to note:

  • Try using printf and scanf to read or input (some say cin, cout can cancel refresh), especially in the time required to read a lot of strings, scanf efficiency improvement is particularly evident.
  • Make good use of map, set, unordered_map and unordered_set. In general, if the key is of type int can be used instead of an array, key type string when it is used map. However, if a large amount of data, it is necessary to use unordered_map. (Map / set the bottom is red-black tree implementation, can guarantee a certain orderliness, unordered_map / unordered_set underlying hash table to achieve, slightly more efficient, but it takes time to build tables)
    concluded that:
    an array In general, only key value does not need to use SET / unordered_set
    Key map when used to string.
    The amount of data (map with timeout), without using unordered_map when ordering. When using unordered_map, try to specify at initialization good size (hash table to reduce the overhead caused by expansion)
    when required ordering (sorting), using the map. (Title will see later)
  • Some small dots, the adjacency list need not use the adjacency matrix, with stringstream string concatenation operator is not overloaded and so
  • Use vector instead of regular arrays. Array competent vector can, but also more convenient.

Of course, sometimes a little convenience inefficient method can be used. Anyway, you can then change the wrong (PAT exam without penalty when) (escape)

Released six original articles · won praise 6 · views 1498

Guess you like

Origin blog.csdn.net/qq_26073557/article/details/104936596