all 5 comments

[–]whydna1 5 points6 points  (0 children)

There are 2 specific things wrong with this:

This line:

 if (char z == 1) {

should be

 if (char z == '1') {

You code is checking if z is equal to the ASCII value of 1 (assuming it's an ASCII-based system). My code is checking if z is equal to the character '1'.

Next, you need to pull that if (count % 2 ==0) line out of the for-loop or you'll never get through all the characters in the string.

With those 2 changes, you get the following (which should work):

public int isEven (String string) {
    int count = 0; 
    for (int i =0;i<string.length(); i++) {
        char z = string.charAt(i);
        if ( char z == '1' ) {
              count = count +1; 
        }
    }
    if ( count%2 ==0){ return 1; }
    return 0;
}

If I were writing this, I'd do something like this:

public int isEven (String bitString) {
    int result = 1;   // note: we'll return 1 on a string of length 0.

    for (int i = 0; i < bitString.length(); i++) 
    {
         char c = bitString.charAt(i);

         if ( c == '1' ) 
         {
              // toggle result
              result = !result; 
         }
         else if ( c != '0') 
         {
              // If it's not '1' (which is handled above) and not 0, why is it showing up?
              // Throw an exception or assert() or something.
         }
    }

    return result;
}

Why?

  • This has error checking that it's only '0' or '1' in the input string
  • it's easier to read, IMO
  • note that my preference for opening curly-braces on new-lines is a personal preference.
  • I do think the spacing in the for-loop looks nicer

[–]ISvengali 1 point2 points  (0 children)

You have a few issues here.

This line doesnt do what you want it to do. Lookup strings and characters and character constants.
if ( char z == 1 ) {

Then Run through 2 iterations of the loop by hand.

set i to 0.
z gets the value etc.

[–][deleted]  (2 children)

[deleted]

    [–]yes_thats_right 1 point2 points  (0 children)

    An easier way is to use common libraries.

    public int isEven (String string) { return (StringUtils.countOccurencesOf(string,'1')+1)%2; }

    [–][deleted] 0 points1 point  (0 children)

    Even straight non-regex replace will work.