Huawei hands-on exercise questions-simple addition and subtraction expression Calculation

Source: Internet
Author: User

Question:

Enter the plus or minus formula for positive integers less than 100 on the keyboard. Write a program to output the computation result string.
The format of the input string is "operand 1 operator operand 2", and "operand" and "operator" are separated by a space.

Note:
1. the operand is a positive integer and computing result overflow is not required.
2. If the input formula format is incorrect, the output result is "0 ".

Required implementation functions:
Void Arithmetic (const char * pinputstr, long linputlen, char * poutputstr );

[Input] pinputstr: input string
Linputlen: length of the input string
[Output] poutputstr: Output string. The space has been opened up and the length of the input string is equal to that of the input string;

[Note] You only need to complete the function algorithm, and there is no IO input or output in the middle.

Example
Input: "4 + 7" output: "11"
Input: "4-7" output: "-3"
Input: "9 + + 7" output: "0" Note: Incorrect format


Analysis: splits the string, obtains two operands and one operator, then makes some illegal judgments, and finally performs operations;


The Code is as follows:

Package com. wenj. test;

/**
*
* @ Author wenj91-PC
*
*/

Public class testarithmetic {

Public static void main (string ARGs []) {
String strin = "9 + + 7 ";
Testarithmetic TA = new testarithmetic ();
System. Out. println (TA. Arithmetic (strin ));
}

Public int Arithmetic (string strin ){
String strtemp = strin;
String [] strarr = strtemp. Split ("");
Int A, B;
Try {
A = integer. parseint (strarr [0]);
B = integer. parseint (strarr [2]);
} Catch (exception e ){
Return 0;
}

String mid = strarr [1];
Char [] STRC = mid. tochararray ();
If (STRC. length> 1 ){
Return 0;
}

Switch (STRC [0]) {
Case '+ ':
Return (A + B );
Case '-':
Return (a-B );
Default:
Return 0;
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.