天天看點

leetcode-cn 回文數判斷

題目描述如圖:

leetcode-cn 回文數判斷

解法基本分為兩類,一類是轉成字元數組,然後逐個比較左邊和右邊的字元,或者是轉成字元串,然後反轉,再進行比較,其本質都是單個字元的比較,大家都能想到,就不寫了。

另一類是直接對數字進行操作,leetcode上有人例舉了,還不錯。我寫完之後,看别人的代碼,簡潔好多,自歎不如(不過我這個是支援負數回文數的?)直接貼代碼:

private static boolean isPalindrome(int value) {
			// 除了 head 剩餘有幾位
			int count = getCount(value);
			// 相當于 2332 => number = 2000;
			int number = (int) Math.pow(10, count);
			for (; value > 9 || value < -9;) {
				// 第一位數
				int head = value / number;
				// 個位數
				int tail = value % 10;
				if (head != tail) {
					return false;
				}
				// 去掉 head 和 tail 例如 2332 => 33
				count -= 2;
				value = (value - (number * head + tail)) / 10;
				int tmpCount = getCount(value);
				// head 之後有一個或多個 0 需要處理下
				if ((tmpCount = (count - tmpCount)) > 0 && value != 0) {
					int pow = (int) Math.pow(10, tmpCount);
					// 除了後 再往回乘 看是否相等
					int tmp = value / pow;
					if (tmp == 0 || value != tmp * pow) {
						return false;
					}
					value = tmp;
				}
				// 更新
				count = getCount(value);
				number = (int) Math.pow(10, count);
			}
	
			return true;
		}
	
	private static int getCount(int value){
		int tmp = value;
		int count = 0;
		while (tmp > 9 || tmp < -9) {
			tmp /= 10;
			count++;
		}

		return count;
	}
           
leetcode-cn 回文數判斷