Java 3-liner


  • 20

    This solution relies on the fact that (a+bi)(c+di) = (ac - bd) + (ad+bc)i.

    public String complexNumberMultiply(String a, String b) {
        int[] coefs1 = Stream.of(a.split("\\+|i")).mapToInt(Integer::parseInt).toArray(), 
              coefs2 = Stream.of(b.split("\\+|i")).mapToInt(Integer::parseInt).toArray();
        return (coefs1[0]*coefs2[0] - coefs1[1]*coefs2[1]) + "+" + (coefs1[0]*coefs2[1] + coefs1[1]*coefs2[0]) + "i";
    }
    

  • 14

    @compton_scatter

    To beat a 3-liner, we have to use 2-liner:

        public String complexNumberMultiply(String a, String b) {
            int[] coef = Stream.of((a+b).split("\\+|i")).mapToInt(Integer::parseInt).toArray();  
            return (coef[0]*coef[2] - coef[1]*coef[3]) + "+" + (coef[1]*coef[2] + coef[0]*coef[3]) + "i";
        }

  • 0

    @zzhai Nice!


  • 8

    @zzhai
    To beat a 2-liner, we have to use a 1-liner:

    String complexNumberMultiply(String a, String b) {
      return ((Function<int[], String>) vs -> (vs[0] * vs[2] - vs[1] * vs[3]) + "+" + (vs[1] * vs[2] + vs[0] * vs[3]) + "i").apply(Arrays.stream((a + b).split("[+i]")).mapToInt(Integer::parseInt).toArray());
    }
    

  • 0

    @paplorinc Makes sense.


  • 0
    P

    this methods compared to String.substring approache makes the running efficiency drops a lot.


  • 0
    K
    This post is deleted!

  • 0
    S

    Elegant solution


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.