it's a "count and say" problem of an interview question and I'm trying the followed code to solve it:
public static String countAndSay(int n) { char[] c = new char[] { '1' }; StringBuffer buffer = null; for (int i = 1; i < n; i++) { buffer = new StringBuffer(); int start = 0; int len = c.length; for (int j = 1; j <= len; j++) { if (j == len || c[j] != c[start]) { buffer.append(j - start); buffer.append(c[start]); start = j; } } c = buffer.toString().toCharArray(); } return new String(c); } public static void main(String[] args) { System.out.println(countAndSay(2)); } here is the description of the problem: The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221,...
1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n, generate the nth sequence.
It's a runnable code. but for the line if (j == len || c[j] != c[start]), if I change it to if (c[j] != c[start] || j == len), there will be an error java.lang.ArrayIndexOutOfBoundsException. I am confused why the different order of two conditions will have different result for an OR operator. Thanks in advance!
||is short circuiting. Ifj == lenis evaluated to true,c[j] != c[start]is not evaluated becausetrue || whatever = true.j == lenis false, thenc[j] != c[start]will be evaluated? thanks @ZouZou