PAT 1023. Have Fun with Numbers

来源:互联网 发布:mac怎么卸载迅雷 编辑:程序博客网 时间:2024/06/05 20:30

1023. Have Fun with Numbers (20)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

Notice that the number 123456789 is a 9-digit number consisting exactly the numbers from 1 to 9, with no duplication. Double it we will obtain 246913578, which happens to be another 9-digit number consisting exactly the numbers from 1 to 9, only in a different permutation. Check to see the result if we double it again!

Now you are suppose to check if there are more numbers with this property. That is, double a given number with k digits, you are to tell if the resulting number consists of only a permutation of the digits in the original number.

Input Specification:

Each input file contains one test case. Each case contains one positive integer with no more than 20 digits.

Output Specification:

For each test case, first print in a line "Yes" if doubling the input number gives a number that consists of only a permutation of the digits in the original number, or "No" if not. Then in the next line, print the doubled number.

Sample Input:
1234567899
Sample Output:
Yes2469135798
考察数据的溢出问题,我的思路是把他分成两个long整形的变量,分别计算,后几位计算结果的进位加到前面
网上说是字符串的乘法,就是一位一位的计算
package p1023;import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);    String rst = null;String s = sc.next();if(s.length() <= 10) {long l = Long.parseLong(s);rst = 2 * l + "";} else {long part1 = Long.parseLong(s.substring(0, s.length()-10));long part2 = Long.parseLong(s.substring(s.length()-10, s.length()));long jinwei = (long) (part2 * 2 / Math.pow(10, 10));long benwei = (long) (part2 * 2 % Math.pow(10, 10));rst = "" + (part1 * 2 + jinwei) + benwei;}if(check(rst, s)) {System.out.println("Yes");} else {System.out.println("No");}System.out.println(rst);}private static boolean check(String s1, String s2) {char[] cs1 = s1.toCharArray();char[] cs2 = s2.toCharArray();int[] cnt1 = new int[10];for(char c : cs1)cnt1[c-'0'] ++;int[] cnt2 = new int[10];for(char c : cs2)cnt2[c-'0'] ++;for(int i=0; i<10; i++)if(cnt1[i]!=cnt2[i])return false;return true;}}
0 0
原创粉丝点击