首页 > 专题系列 > Java解POJ > POJ 1350 Cabric Number Problem [解题报告] Java
2013
11-09

POJ 1350 Cabric Number Problem [解题报告] Java

Cabric Number Problem

问题描述 :

If we input a number formed by 4 digits and these digits are not all of one same value, then it obeys the following law. Let us operate the number in the following way:

(1) Arrange the digits in the way from bigger to smaller, such that it forms the biggest number that could be made from these 4 digits;

(2) Arrange the digits in the way from smaller to bigger, such that it forms the smallest number that could be made from these 4 digits (If there is 0 among these 4 digits, the number obtained may be less than four digits);

(3) Find the difference of these two numbers that is a new four digital number.

Repeat the above process, we can finally always get the result 6174 or 0.

Please write the program to realize the above algorithm.

输入:

Each case is a line of an integer.-1 denotes the end of input.

输出:

If the integer is formed exactly by 4 digits and these digits are not all of one same value, then output from the program should show the procedure for finding this number and the number of repetition times. Otherwise output “No!!”.

样例输入:

5364
2221
4444
-1

样例输出:

N=5364:
6543-3456=3087
8730-378=8352
8532-2358=6174
Ok!! 3 times
N=2221:
2221-1222=999
999-999=0
Ok!! 2 times
N=4444:
No!!

解题代码:

//* @author: Yeming Hu"[email protected]"
import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
	while(true)
	{
	    String num = sc.next();
	    if(num.equals("-1"))
	    {
	        break;
	    }
	    System.out.println("N="+num+":");
	    if(num.length()!=4||(num.charAt(0)==num.charAt(1)&&
	        num.charAt(1)==num.charAt(2)&& num.charAt(2)==num.charAt(3)))
	    {
		System.out.println("No!!");
	    }else
	    {
	        int count = 0;
	        while(true)
		{
		    char[] chs = new char[num.length()];
		    for(int i = 0;i < num.length(); i++)
		    {
		        chs[i] = num.charAt(i);
		    }
		    Arrays.sort(chs);
		    int small = Integer.parseInt(new String(chs));
		    for(int i=0;i< chs.length/2;i++)
		    {
		        char temp = chs[i];
			chs[i] = chs[chs.length-1-i];
			chs[chs.length-1-i] = temp;
		    }
		    int big = Integer.parseInt(new String(chs));
		    int diff = big - small;
		    num = Integer.toString(diff);
		    count++;
		    System.out.println(big+"-"+small+"="+diff);
		    if(diff==6174 || diff == 0)
		    {
		        System.out.println("Ok!! " + count  + " times");
			break;
		    }
		}
	    }
	}
    }
}

  1. Often We don’t set up on weblogs, but I would like to condition that this established up really forced me individually to do this! considerably outstanding publish