Why does my bit manipulation solution got wrong answer? Anyone help me plz?


  • 0
    Y
    public static boolean isPalindrome(ListNode head) {
    		if (head == null || head.next == null) {
    			return true;
    		}
    		int len = getLen(head);
    		int res = 0;
    		ListNode backup = head;
    		if (len % 2 == 0) {
    			while (backup != null) {
    				res = res ^ backup.val;
    				backup = backup.next;
    			}
    			if (res == 0) {
    				return true;
    			} else {
    				return false;
    			}
    		} else {
    			int count = 0;
    			while (backup != null) {
    				if (count == len / 2) {
    					backup = backup.next;
    				}
    				res = res ^ backup.val;
    				backup = backup.next;
    				count++;
    			}
    			if (res == 0) {
    				return true;
    			} else {
    				return false;
    			}
    		}
    	}
    
    	public static int getLen(ListNode node) {
    		int len = 0;
    		while (node != null) {
    			len++;
    			node = node.next;
    		}
    		return len;
    	}

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.