Given two strings representing two complex numbers.
You need to return a string representing their multiplication. Note i2
= -1 according to the definition.
其实可以用一次遍历的方法求 但是我觉得这样的代码复用度不高,所以写了取不同part的函数,代价是牺牲一定的时间效率取得更高的扩展性。
class Solution {
public String complexNumberMultiply(String a, String b) {
StringBuilder sb = new StringBuilder();
int real1 = get_part(a,true);
int real2 = get_part(b,true);
int imag1=get_part(a,false);
int imag2=get_part(b,false);
int real = real1*real2-imag1*imag2;
int imag = real1*imag2+real2*imag1;
sb.append(real);
sb.append('+');
sb.append(imag);
sb.append('i');
return sb.toString();
}
private int get_part(String a ,boolean real)
{
StringBuilder sb = new StringBuilder();
int pos = 0;
for(int i=0;i<a.length();i++)
{
char ch =a.charAt(i);
if(real)
{
if(ch=='+')
break;
else
{
sb.append(ch);
}
}
else
{
if(ch!='+')
continue;
i++;
while(a.charAt(i)!='i')
{
sb.append(a.charAt(i));
i++;
}
}
}
return Integer.parseInt(sb.toString());
}
}