My Swift Solution


  • 0
    J
    func isPalindrome(x: Int) -> Bool {
            if x < 0 {
                return false
            }
    
            if x < 10 {
                return true
            }
    
            var div = 1
            while x / div >= 10 {
                div *= 10
            }
    
            var inputValue = x
            while inputValue > 0 {
                let l = inputValue / div
                let r = inputValue % 10
                if l != r {
                    return false
                }
    
                inputValue = (inputValue % div) / 10
                div /= 100
            }
    
            return true
        }

  • 0
    L
    public class Solution {
        public boolean isPalindrome(ListNode head) {
            if(head == null || head.next == null) return true;
            
            ListNode tail = head;
            int length = 0;
            while(tail != null){
                length++;
                tail = tail.next;
            }
            int mid = length/2;
            
            ListNode a = null;
            ListNode b = head;
            ListNode c = null;
            int i = 0;
            
            while(i<mid && b!=null){
                c = b.next;
                b.next = a;
                a = b;
                b = c;
                i++;
            }
            if(length%2 != 0) b = b.next;
            while(a!=null && b!=null){
                if(a.val != b.val) return false;
                a = a.next; b = b.next;
            }
            return true;
        }
    }

Log in to reply
 

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