解法一

注意substring和indexOf等方法的使用。

  1. class Solution {
  2. public String complexNumberMultiply(String a, String b) {
  3. ComplexNumber c1 = new ComplexNumber(a);
  4. ComplexNumber c2 = new ComplexNumber(b);
  5. return c1.multiply(c2).toString();
  6. }
  7. }
  8. class ComplexNumber {
  9. public Integer realPart;
  10. public Integer imaginaryPart;
  11. public ComplexNumber(Integer realPart, Integer imaginaryPart) {
  12. this.realPart = realPart;
  13. this.imaginaryPart = imaginaryPart;
  14. }
  15. public ComplexNumber(String s) {
  16. int pos1 = s.indexOf('+');
  17. int pos2 = s.indexOf('i');
  18. realPart = Integer.parseInt(s.substring(0, pos1));
  19. imaginaryPart = Integer.parseInt(s.substring(pos1 + 1, pos2));
  20. }
  21. public ComplexNumber multiply(ComplexNumber c) {
  22. return new ComplexNumber(
  23. realPart * c.realPart - imaginaryPart * c.imaginaryPart,
  24. realPart * c.imaginaryPart + imaginaryPart * c.realPart);
  25. }
  26. @Override
  27. public String toString() {
  28. return realPart.toString() + "+" + imaginaryPart.toString() + "i";
  29. }
  30. }