Reputation:
While studying for interview questions, I came across this piece of code on the internet:
class Solution {
public:
string complexNumberMultiply(string a, string b) {
//I initially did it using substring (searching for "+" etc.)
//But it is super easy using stringstreams
stringstream aa(a), bb(b), ans;
int ra, rb, ia, ib;
char buff;
aa>>ra>>buff>>ia>>buff;
bb>>rb>>buff>>ib>>buff;
ans<<ra*rb-ia*ib<<"+"<<ra*ib+rb*ia<<"i";
return ans.str();
}
};
This snippet multiplies two input strings represent complex numbers of the form a+bi
. Thus, if the input is 1+1i
and 1+1i
, then the output generated by this code is 0+2i
(because i^2=-1
).
I do understand why stringstreams aa
and bb
have been used and how they work; but I fail to understand the role of char buff
. Consider the statement:
aa>>ra>>buff>>ia>>buff;
Here, from the stringstream aa
we first read the rational part ra
(then buff
for a plus "+"?), then the imaginary part ia
and then the buff
again (maybe for \n
?). Is my understanding correct? If I remove the buffers though, it works fine for the inputs like 1+2i
but fails where imaginary part is negative like 1+-2i
(yeah, not 1-2i
).
Kindly let me know if my understanding is correct. Thank you!
Upvotes: 0
Views: 307
Reputation: 11484
Yes, your understanding is correct. operator >>
is common for each input stream (ancestor of std::istream
) and it uses std::num_get::get
for integers.
Accoding to stage 2 logic and positive imaginary part aa >> ra >> rb
will run like this:
2 -> accumulated to storage "2"
(because 2 matches one of "0123456789abcdefxABCDEFX+-")
+ -> ignored, because "2+" is not valid integer for scanf, so first
operator >> terminates here
+ -> accumulated to storage "+"
3 -> accumulated to storage "+3"
i -> ignored, because "+3i" is not a valid integer, so we
can scan "+3" as integer 3 and put it to rb
Negative imaginary part is broken for second integer:
+ -> accumulated to storage "+"
- -> "+-" is not a valid scanf, so we should terminate second
operator >> while putting 0 to ra because "+" is also is not
an integer
So by adding explicit reading of single character, you read '+' in 2nd operator >>
and can read "3" or "-3" correctly in 3rst call to operator >>
Upvotes: 0
Reputation: 180415
You are almost correct. When you have a string like 1+1i
you have two valid integers and two valid characters. So aa>>ra
reads the first integers into ra
leaving you with +1i
. Then >>buff
reads the character (+
) into buff leaving 1i
in the stream. Then >>ia
reads the next integer and leaves i
in the stream. Then >>buff
consumes the i
left in the stream.
Generally when doing something like this I like to use a more descriptive variable name. I like to use eater
a lot as it implies that I'm just eating the input(throwing it away). If I know what the input will look like then even more descriptive names are nice like sign
/operator
/imaginary_part
.
Upvotes: 3