Results 1 to 2 of 2

Thread: simple code

  1. #1
    elizabeth is offline Member
    Join Date
    Jul 2007
    Posts
    40
    Rep Power
    0

    Default simple code

    The following function determine if its parameter is a string which reads exactly the same forward or backward. There is an error in the code.

    Java Code:
    boolean isPalindrome(String s) {
    int i=0, j = s.length( ) -1;
    while ( i !=j && s.charAt(i)==s.charAt(j)) {
    i++;
    j--;
    }
    return (i==j);
    }
    help please

  2. #2
    leonard is offline Member
    Join Date
    Jul 2007
    Posts
    43
    Rep Power
    0

    Default

    You code will work only if the string lenght is odd. Wont work if it is even
    Java Code:
    boolean isPalindrome(String s) {
    int i=0, j = s.length( ) -1;
    while ( i !=j && s.charAt(i)==s.charAt(j)) {
    i++;
    j--;
    }
    return (i==j);
    }
    
    try these changes it will work
    
    boolean isPalindrome(String s) {
    int i=0, j = s.length( ) -1;
    while ( i !=j && s.charAt(i)==s.charAt(j)) {
    // change the condition here from i!=j to i<=j
    
    i++;
    j--;
    }
    return (i==j);
    //Change the condition here from i==j to i>j
    
    }
    good luck

Similar Threads

  1. Replies: 3
    Last Post: 12-12-2008, 01:12 PM
  2. Peculiarty in code of simple program...
    By Kreuz14 in forum New To Java
    Replies: 4
    Last Post: 01-23-2008, 04:27 AM
  3. simple problem - code wont compile
    By dirtycash in forum New To Java
    Replies: 1
    Last Post: 11-20-2007, 06:49 PM
  4. problem with a simple java code
    By boy22 in forum New To Java
    Replies: 2
    Last Post: 08-03-2007, 03:46 AM
  5. Replies: 1
    Last Post: 04-26-2007, 04:52 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •