2

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!

4
  • 6
    || is short circuiting. If j == len is evaluated to true, c[j] != c[start] is not evaluated because true || whatever = true. Commented Feb 24, 2014 at 6:50
  • so only if j == len is false, then c[j] != c[start] will be evaluated? thanks @ZouZou Commented Feb 24, 2014 at 6:53
  • 1
    Google lazy evaluation. Commented Feb 24, 2014 at 6:53
  • @Zihan Yes. For more informations, you can also consult the JLS: docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.24. Commented Feb 24, 2014 at 6:55

3 Answers 3

2
if (j == len || c[j] != c[start]) true---^ ^------Expression is NOT evaluated if (j == len || c[j] != c[start]) false---^ ^------Expression is evaluated 

If the first expression is true then the jvm will not go to check the second expression in case of OR operator

Sign up to request clarification or add additional context in comments.

Comments

0

If the first expression evaluates to 'true', then the other expression is ignored when the expressions are separated by OR operator

Comments

0

The Or operator is evaluated so that the options are evaluated in order from left to right, and when the first one is true, the whole statement is true. That means if you have (valid-statement || invalid-statement) and valid-statement is true, the invalid-statement never gets evaluated.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.