Given a sequence of number: 1, 11, 21, 1211, 111221, …

The rule of generating the number in the sequence is as follow:

1 is "one 1" so 11.

11 is "two 1s" so 21.

21 is "one 2 followed by one 1" so 1211.

Find the nth number in this sequence.

  public String countAndSay(int n) {
    if (n < 1) {
      return "";
    }
    StringBuilder sb = new StringBuilder();

    sb.append(1);
    int count = 1;
    for (int j = 2; j <= n; j++) {
      StringBuilder sb2 = new StringBuilder();
      for (int i = 0; i < sb.length(); i++) {
        if (i + 1 < sb.length() && sb.charAt(i) == sb.charAt(i + 1)) {
          count++;
          continue;
        }
        sb2.append(count).append(sb.charAt(i));
        count = 1;
      }
      sb = sb2;
    }

    return sb.toString();
  }

results matching ""

    No results matching ""