英雄会编程挑战之回文数

题目详情

如果一个数正着读和反着读一样大,则这个数叫做回文数,例如121是回文数,123454321是回文数。


现给定一个正整数x,输出一个回文数y,要求y > x,并且组成x的所有数字之和与组成y的所有数字之和相等,以及y > x。

x在10^1000以内,因为数字较大,我们用字符串作为输入和输出。

如果无解,请输出Impossible。如果有多个y,输出最小的那个。


例如:

输入919,输出14941

输入1,输出Impossible


解析:

题目本身没有什么难度,当然有可能是我理解错误。代码随手写的,为了通过网上编译全部写道一个方法里面,层次上有点乱。代码复杂度为O(N);

代码如下:

public class CopyOfTest3 {
	public static String palindrom(String a) {
		String result = "";
		char[] ch = a.toCharArray();
		int num = 0;
		for (int i : ch) {
			num += (i - 48);
		}
		if (num == 1) {
			result = "Impossible";
			return result;
		}
		switch (ch.length) {
		case 2:
			if (num % 2 == 0) {
				// 首先判断2位的长度是否可以
				if (num >= (ch[0] - 47) * 2) {
					result = num / 2 + "" + num / 2;
				} else {
					int i = (num - 9) / 2;
					i = (i <= 0) ? 1 : i+1;
					result = i + "" + (num - 2 * i) + "" + i;
				}
			} else {
				int i = (num - 9) / 2;
				i = (i <= 0) ? 1 : i;
				result = i + "" + (num - 2 * i) + "" + i;
			}
			break;
		case 3:
			if (!(ch.length == 1 || ch.length == 2 || ch[0] - 48 == 9)) {

				int i = ch[0] - 47;
				int ii = num - 2 * i;
				if (ii >= 0 && ii < 10) {
					result = i + "" + ii + "" + i;
					return result;
				}
			}
			if (num % 2 == 0) {
				int i = num - 18;

				i = (i <= 0) ? 2 : i;
				System.out.println("i:" + i);
				int ii = (num - 2) / 2;
				switch (i / 2) {
				case 1:
					result = "1" + ii + "" + ii + "" + "1";
					break;
				case 2:
					result = "2" + ii + "" + ii + "" + "2";
					break;
				case 3:
					result = "3" + ii + "" + ii + "" + "3";
					break;
				default:
					result = "4" + ii + "" + ii + "" + "4";
					break;
				}
			} else {
				int i = (num - 11) / 2;

				int ii = (i <= 0) ? 0 : i;

				int iii = num - 2 - (2 * ii);
				switch (i / 2) {
				case 1:
					result = "1" + ii + "" + iii + "" + ii + "" + "1";
					break;
				case 2:
					result = "1" + ii + "" + iii + "" + ii + "" + "1";
					break;
				case 3:
					result = "1" + ii + "" + iii + "" + ii + "" + "1";
					break;
				case 4:
					result = "1" + ii + "" + iii + "" + ii + "" + "1";
					break;
				case 5:
					result = "1" + ii + "" + iii + "" + ii + "" + "1";
					break;
				case 6:
					result = "1" + ii + "" + iii + "" + ii + "" + "1";
					break;
				case 7:
					result = "1" + ii + "" + iii + "" + ii + "" + "1";
					break;
				case 8:
					result = "1" + ii + "" + iii + "" + ii + "" + "1";
					break;
				default:
					result = "1" + ii + "" + iii + "" + ii + "" + "1";
					break;
				}
			}
			break;
		default:
			break;
		}

		return result;
	}

	// start 提示:自动阅卷起始唯一标识,请勿删除或增加。
	public static void main(String args[]) {
		System.out.println(System.currentTimeMillis());
		System.out.println(palindrom("999"));
		System.out.println(System.currentTimeMillis());
	}
	// end //提示:自动阅卷结束唯一标识,请勿删除或增加。
}


你可能感兴趣的:(英雄会编程挑战之回文数)