【Leetcode-easy】Palindrome Number

來源:互聯網
上載者:User

標籤:

思路:除和求餘 取得首位和末尾 比較是否相等。

 1     public boolean isPalindrome(int x){ 2         if(x<0){ 3             return false; 4         } 5         int div=1; 6         while(x/div>=10){ 7             div*=10; 8         } 9         while(x!=0){10             int left=x/div;11             int right=x%10;12             if(left!=right){13                 return false;14             }15             x=(x%div)/10;//去掉最高位和最低位16             div/=100;17         }18         return true;19     }

其他思路:http://m.blog.csdn.net/blog/yike1207/44307819博文總結了幾種方法(整數反轉、轉化為字串處理,取高低位比較)該作者認為上述方法都用到了額外的儲存空間,不用額外的儲存空間一種方法是通過遞迴,並修改引用參數值。

 1 bool isPalindrome(int x, int &y) {    2   // y為必須為引用和指標型可改變的變數 3   if (x < 0) return false; 4   if (x == 0) return true; 5   if (isPalindrome(x/10, y) && (x%10 == y%10)) { 6     // 每次執行到 x%10 == y%10 的時候 x 為前i位,y表示前(n+1-i)位 7     y /= 10;                8     return true; 9   } else {10     return false;11   }12 }13 bool isPalindrome(int x) {14   return isPalindrome(x, x);15 }

 

【Leetcode-easy】Palindrome Number

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.