首页 > 试题广场 >

The Black Hole of Numbers (20)

[编程题]The Black Hole of Numbers (20)
  • 热度指数:2078 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
For any 4-digit integer except the ones with all the digits being the same, if we sort the digits in non-increasing order
first, and then in non-decreasing order, a new number can be obtained by taking the second number from the first
one. Repeat in this manner we will soon end up at the number 6174 -- the "black hole" of 4-digit numbers. This
number is named Kaprekar Constant.

For example, start from 6767, we'll get:

7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
... ...

Given any 4-digit number, you are supposed to illustrate the way it gets into the black hole.

输入描述:
Each input file contains one test case which gives a positive integer N in the range (0, 10000).


输出描述:
If all the 4 digits of N are the same, print in one line the equation "N - N = 0000". Else print each step of calculation in a line until 6174 
comes out as the difference. All the numbers must be printed as 4-digit numbers.
示例1

输入

6767

输出

7766 - 6677 = 1089<br/>9810 - 0189 = 9621<br/>9621 - 1269 = 8352<br/>8532 - 2358 = 6174
本题要注意的就是输入样例不一定是一个4位数,所以要自动补0填充
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main() {
    string digit;
    cin >> digit;
    if (digit.size() < 4)
        digit.insert(digit.begin(), 4 - digit.size(), '0');   //补全4-digit number
    int dit = stoi(digit);
    if (dit%1111==0) 
        printf("%04d - %04d = %04d\n", dit, dit, 0);
    else {
        int d1, d2, ans;
        while (1) {
            sort(digit.begin(), digit.end());
            d2 = stoi(digit);
            reverse(digit.begin(), digit.end());
            d1 = stoi(digit);
            ans = d1 - d2;
            printf("%04d - %04d = %04d\n", d1, d2, ans);
            if (ans == 6174)
                break;
            digit = to_string(ans);
        }
    }
    return 0;
}

发表于 2019-12-03 14:21:13 回复(0)
首先判是否为1111,我之前就是因为没有判断是1111而超时
然后进行最大排序处理
最小排序处理
最后循环到6174程序结束



import java.util.*;
public class Main {
public static void main(String[] args)
{
    Scanner in=new Scanner(System.in);
    int  num=in.nextInt();
    int  [] n=new int[4];
    if (isSame(num)) {
        System.out.println(num +" - "+ num + " = 0000");
    }
    else
    {
        for (; ; ) {
            array(n, num);
            Arrays.sort(n);
            num = add(n);
            zero(add(n));
            System.out.print(num + " - ");
            invertUsingFor(n);
            num -= add(n);
            zero(add(n));
            System.out.print(add(n) + " = ");
            zero(num);
            System.out.println(num);
            if (num == 6174) {
                break;
            }

        }
    }
}
public static void invertUsingFor(int [] digits) {

    int t = digits[0];
    digits[0] = digits[3];
    digits[3] = t;
    t = digits[1];
    digits[1] = digits[2];
    digits[2] = t;
}

public static void array(int []n,int num)
{
    for (int i = 0; num!=0; i++)
    {
        n[i] = num % 10;
        num /= 10;

    }
}
public static int add(int []n)
{
    int temp=0;
    for (int i = 3; i >=  0; i--)
    {
        temp*=10;

        temp+=n[i];

    }
    return temp;
}
public static void zero(int n)
{
    if(n<10)
    {
        System.out.print("000");
    }
    else if(n>10&&n<100)
    {
        System.out.print("00");
    }
    else if(n>100&&n<1000)
    {
        System.out.print("0");
    }

}
public static boolean isSame(int num) {
    int a1 = num / 1000;
    int a2 = num % 1000 / 100;
    int a3 = num % 100 / 10;
    int a4 = num % 10;
    if (a1 == a2 && a1 == a3 && a1 == a4)
        return true;
    return false;
}
}

发表于 2018-10-08 21:13:48 回复(0)
讲真我讨厌这道题 测试点有猫饼
输入时候不一定是4个数字的,比如645就是645,不是0645
我在那想了好久怎么会超时= =然后我研究了半天数字演变的规律想直接出答案。。
很惭愧的试了几十组没找到规律,只发现后面顺序仅和数位差值有关
贴上老老实实的笨办法
代码如下:
#include <iostream>
#include <memory.h>
#include <algorithm>
using namespace std;

inline int char2int(char* str) {
	int num = str[0] - '0';
	num *= 10;
	num += str[1] - '0';
	num *= 10;
	num += str[2] - '0';
	return num * 10 + str[3] - '0';
}

inline void int2char(int num, char* str) {
	str[3] = num % 10 + '0';
	num /= 10;
	str[2] = num % 10 + '0';
	num /= 10;
	str[1] = num % 10 + '0';
	str[0] = num / 10 + '0';
}

inline bool decrease(char a, char b) {
	return a > b;
}

int main(int argc, const char* argv[]) {
	ios::sync_with_stdio(false);
	char str[5], sortStr[5];
	str[4] = sortStr[4] = '\0';
	int num;
	cin >> num;
	int2char(num, str);
	if (!(num % 1111)) {
		cout << num << " - " << num << " = 0000";
		return 0;
	}
	while (num - 6174) {
		memcpy(sortStr, str, 4);
		sort(str, str + 4, decrease);
		num = char2int(str);
		sort(sortStr, sortStr + 4);
		int sortNum = char2int(sortStr);
		cout << str << " - " << sortStr << " = ";
		num -= sortNum;
		int2char(num, str);
		cout << str << endl;
	}
	//system("pause");
	return 0;
}

编辑于 2017-03-01 14:11:05 回复(0)
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
	int x,y,z;
	cin>>x;
	int a[4];
	if(x==6174) x=1674;
	while(x!=6174){
		a[0]=x/1000;a[1]=x/100%10;a[2]=x/10%10;a[3]=x%10;
		sort(a,a+4);
		if(a[0]==a[3]){
			printf("%04d - %04d = 0000",x,x);
			return 0;
		}
		y=a[3]*1000+a[2]*100+a[1]*10+a[0];
		z=a[0]*1000+a[1]*100+a[2]*10+a[3];
		x=y-z;
		printf("%04d - %04d = %04d\n",y,z,x);
	}
}

发表于 2020-07-23 20:09:47 回复(0)
import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner in=new Scanner(System.in);
        char[] numbers=buling(in.nextInt()).toCharArray();
        Arrays.sort(numbers);
        int result=getMax(numbers)-getMin(numbers);
        if(result!=0){
            System.out.println(buling(getMax(numbers))+" - "+buling(getMin(numbers))+" = "+buling(result));
        }
        while(result!=6174){
            if(result==0){
                System.out.println(getMax(numbers)+" - "+getMin(numbers)+" = 0000");
                break;
            }
            char[] tempChar=buling(result).toCharArray();
            Arrays.sort(tempChar);
            result=getMax(tempChar)-getMin(tempChar);
            System.out.println(buling(getMax(tempChar))+" - "+buling(getMin(tempChar))+" = "+result);
        }
    }

    public static String buling(int number){
        String temp=String.valueOf(number);
        int size=temp.length();
        if(size<4){
            for(int i=0;i<4-size;i++){
                temp="0"+temp;
            }
        }
        return temp;
    }

    public static int getMin(char[] numbers){
        String result="";
        for(int i=0;i<numbers.length;i++){
            result+=numbers[i];
        }
        return Integer.valueOf(result);
    }

    public static int getMax(char[] numbers){
        String result="";
        for(int i=numbers.length-1;i>=0;i--){
            result+=numbers[i];
        }
        return Integer.valueOf(result);
    }
}

发表于 2018-10-05 19:45:36 回复(0)
#include <stdio.h>
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <map>
using namespace std;

void sortx(int &a,int &b)
{
int chara[4];
chara[0] = a % 10;
chara[1] = a % 100 / 10;
chara[2] = a % 1000 / 100;
chara[3] = a / 1000;
sort(chara, chara + 4);
a = chara[3] * 1000 + chara[2] * 100 + chara[1] * 10 + chara[0];
b = chara[0] * 1000 + chara[1] * 100 + chara[2] * 10 + chara[3];
}

int main()
{
int data, datar;
cin >> data;
sortx(data, datar);
if (data == datar)
printf("%04d - %04d = 0000\n", data, datar);
else
{
do
{
printf("%04d - %04d = %d\n", data, datar, data - datar);
data = (data - datar);
sortx(data, datar);
}while (data- datar!= 6174);
printf("%04d - %04d = %d\n", data, datar, data - datar);
}
return 0;
}
发表于 2017-09-10 14:42:12 回复(0)
num = input()
num = '%04d'% num
temp = sorted(list(str(num)))
big = int(''.join(temp[::-1]))
small = int(''.join(temp))
num = big - small
whilenum and num != 6174:
    print '%04d - %04d = %04d'% (big, small, num)
    temp = sorted(list(str(num)))
    big = int(''.join(temp[::-1]))
    small = int(''.join(temp))
    num = big - small
print '%04d - %04d = %04d'% (big, small, num)

发表于 2016-06-12 01:00:24 回复(0)
#include <iostream>
#include <algorithm>
using namespace std;
bool cmp(int a,int b){
    return a>b;
}
int changenum(int s[]){
    int n=0;
    for(int i=0;i<4;i++)
        n=n*10+s[i];
    return n;
}
void toarray(int n,int s[]){
    for(int i=0;i<4;i++){
        s[i]=n%10;
        n/=10;
    }
}
int main(){
    int n,a,b,s[5];
    cin>>n;
    while(n!=0 && n!=6174){
        toarray(n,s);
        sort(s,s+4);
        a=changenum(s);
        sort(s,s+4,cmp);
        b=changenum(s);
        n=a-b;
        printf("%04d - %04d = %04d\n",a,b,n);
    }
    return 0;
}


发表于 2018-02-14 18:13:23 回复(2)
import sys
n_str = input().strip()
n = int(n_str)
if n == 0:
    print("0000 - 0000 = 0000")
    exit(0)
if len(n_str) == 4:
    if n_str[0] == n_str[1] == n_str[2] == n_str[3]:
        print("{:04} - {:04} = 0000".format(int(n), int(n)))
        exit(0)
k = int(n_str)
if k == 6174:
    print('7641 - 1467 = 6174')
while k != 6174 and k > 0:
    lst = list(str(k))
    if len(lst) < 4:
        for i in range(4-len(lst)):
            lst.append('0')
    l1 = sorted(lst, reverse=True)
    l2 = sorted(lst)
    a, b = int("".join(l1)), int("".join(l2))
    k = a-b
    print('{:04} - {:04} = {:04}'.format(a, b, k))

发表于 2021-01-20 17:55:44 回复(0)
#include <stdio.h>
int main()
{
    int num,arr[4],i,j,tmp,inc=0,dec=0,n;
    scanf("%d",&num);
    while(dec-inc!=6174)
    {
        tmp=num;
        for(i=0;i<4;i++)
        {
            arr[i]=tmp%10;
            tmp=tmp/10;
        }
        for(i=0;i<3;i++)
        {
            for(j=i+1;j<4;j++)
            {
                if(arr[i]>arr[j])
                {
                    n=arr[i];
                    arr[i]=arr[j];
                    arr[j]=n;
                }
            }
        }
        inc=arr[0]*1000+arr[1]*100+arr[2]*10+arr[3];
        dec=arr[3]*1000+arr[2]*100+arr[1]*10+arr[0];
        if(dec==inc)
        {
            printf("%04d - %04d = %04d\n",dec,inc,dec-inc);
            break;
        }
        else
        {
            printf("%04d - %04d = %04d\n",dec,inc,dec-inc);
        }
        num=dec-inc;
    }
    return 0;
}

发表于 2020-04-26 09:45:02 回复(0)
//这个题看着简单,但是想要快速ac还是不行。。。
//一开始答案错误是因为没有考虑到非四位的数要补0,比如666等。
//最后发现超时,我还纳闷这怎么会超时,又没什么算法。然后发现题目给出的是(0,10000)。因此可能存在1111等数字,是我没仔细看题,粗心了。。。。
//还有个问题就是PTA第五个测试点总是过不了,答案错误,不知道这个测试案例是什么?
#include<iostream>
(720)#include<vector>
#include<algorithm>
(831)#include <string>
using namespace std;
int non_dec(string n) {
	vector<int>tmp;
	int sizes = n.size();
	while (sizes < 4) {
		n = "0" + n;
		sizes++;
	}
	sort(n.begin(), n.end());
	return (n[0]-'0')*1000+ (n[1] - '0') *100+ (n[2] - '0') *10+ (n[3] - '0');
}
int non_inc(string n) {
	vector<int>tmp;
	int sizes = n.size();
	while (sizes < 4) {
		n = "0" + n;
		sizes++;
	}
	sort(n.begin(), n.end());
	return (n[3] - '0') * 1000 + (n[2] - '0') * 100 + (n[1] - '0') * 10 + (n[0] - '0');
}
int main() {
	string n;
	cin >> n;
	if (n == "0"||(non_inc(n)== non_dec(n))) {
		printf("%04d - %04d = 0000",non_inc(n), non_inc(n));
	}
	else {
		while (n != "6174"){
			int N1 = non_inc(n);
			int N2 = non_dec(n);
			printf("%04d - %04d = %04d\n", N1, N2, N1 - N2);
			n = to_string(N1 - N2);
		}
	}
}


发表于 2020-03-31 18:40:11 回复(0)
nlst,boo = [],True n = input() n = int(n) n = "%04d"%n
while True:     for i in n:         nlst.append(i)     n1,n2 = '',''     nlst.sort()     for i in nlst:         n1+=i     nlst.reverse()     for i in nlst:         n2+=i     if n1==n2:         boo = False         print(n1+" - "+n1+" = 0000")         break     else:         n = "%04d"%(int(n2)-int(n1))         if boo:             print(n2+" - "+n1+" = "+n)         nlst = []         if n=='6174':            break

发表于 2018-12-10 11:38:09 回复(0)
要是输入为6174的话,应该输出什么?
发表于 2018-06-05 21:23:34 回复(1)
n=int(input())
while n!=0 and n!=6174:
    x = int(''.join(sorted('{:04d}'.format(n), reverse=True)))
    y = int(''.join(sorted('{:04d}'.format(n))))
    n = x-y
    print('{:04d} - {:04d} = {:04d}'.format(x,y,n))

发表于 2018-05-02 17:14:13 回复(1)

分成了几个函数来写,看起来很简单。

# include <cstdio>
# include <cstdlib>

int m, n;
int digits[4];

void int2digs(int num) {
    for (int i = 0; i < 4; i++) {
        digits[i] = num % 10;
        num /= 10;
    }
}

int compar(const void *a, const void *b) {
    return *(int*)a - *(int*)b;
}

void reverseDigs() {
    int t = digits[0];
    digits[0] = digits[3];
    digits[3] = t;
    t = digits[1];
    digits[1] = digits[2];
    digits[2] = t;
}

int digs2int() { //digits[0][1][2][3]
    int num = 0;
    for (int i = 0; i < 4; i++) {
        num = num * 10 + digits[i];
    }
    return num;
}

int main() {
    scanf("%d", &m);
    n = -9999;
    while (1) {
        int2digs(m);
        qsort(digits, 4, sizeof(int), compar);
        n = digs2int();
        reverseDigs();
        m = digs2int();
        printf("%04d - %04d = %04d\n", m, n, m - n);
        m -= n;
        if (m == 6174 || m == 0) {
            break;
        }
    }

    return 0;
}
发表于 2018-03-15 20:46:53 回复(0)
#include<iostream>
#include<algorithm>
using namespace std;

int main()
{
    int a[4];
    int N;
    cin >> N;

    do
    {
        for(int i = 0; i < 4; i++)
        {
            a[i] = N % 10;
            N /= 10;
        }
        sort(a, a+4);
        int a1 = 0, a2 = 0;
        for(int i = 0; i < 4; i++)
        {
            a1 = a1*10 + a[i];
            a2 = a2*10 + a[3-i];
        }
        printf("%.04d - %.04d = %.04d\n", a2, a1, a2-a1);
        N = a2-a1;
    }while(N != 6174 && N != 0);                    //N != 0千万别落下, 要不就死循环了

    system("pause");
    return 0;
}
发表于 2018-03-13 09:21:04 回复(0)

import java.util.Arrays;


public class Main {

    public static void main(String[] args) {

        try (java.util.Scanner input = new java.util.Scanner(System.in)) {

            int N = input.nextInt();

            boolean isEachDigitSame = true;

            int a = N / 10;

            int b = N % 10;

            for (int i = 0; i < 3; i++) {

                if (a % 10 == b) {

                    a = a / 10;

                } else {

                    isEachDigitSame = false;

                }

            }

            

            if (isEachDigitSame) {

                System.out.printf("%04d - %04d = %04d", N, N, 0);

                return;

            }

            

            while (true) {

                int nonIncrNum = sort(N, "DECR");

                int nonDecrNum = sort(N, "INCR");

                int result = nonIncrNum - nonDecrNum;

                if (result == 6174) {

                    System.out.printf("%04d - %04d = %04d", nonIncrNum, nonDecrNum, result);

                    break;

                } else {

                    System.out.printf("%04d - %04d = %04d\n", nonIncrNum, nonDecrNum, result);

                    N = result;

                }

            }

        }

    }


    // 排序

    public static int sort(int num, String order) {

        // 将 num 转成 Integer 数组

        Integer[] numArray = new Integer[4];

        for (int i = 3; i >= 0; i--) {

            numArray[i] = num % 10;

            num = num / 10;

        }


        // 排序

        if ("INCR".equals(order)) {

            Arrays.sort(numArray, (i1, i2) -> i1 > i2 ? 1 : -1);

        } else if ("DECR".equals(order)) {

            Arrays.sort(numArray, (i1, i2) -> i1 > i2 ? -1 : 1);

        }

        

        // 将数组转换成整数

        int sortedNum = 0;

        for (Integer i : numArray) {

            sortedNum = sortedNum * 10 + i;

        }


        return sortedNum;

    }

}


发表于 2018-02-10 17:03:39 回复(0)
题意:有个性质:
           将4位数,将其各数位按递增、递减排列,分别形成两个数,然后将两个数相减。
           重复上述过程,直至这个数变成6174
       求这个变成6174的过程
思路: 为了对4位数的各个数字进行排序,我将4位数转成用数组存储各个数字,这样便可进行排序
            还要将排序完后的数字,重新转换成4位数。于是就写两个函数,数转数组,数组转数便可。

#include <cstdio>
#include <algorithm>
using namespace std;

bool cmp(int a, int b)     //递减排序cmp
{
return a > b;
}

void to_array(int n, int num[])  //将n的每一位存到num数组中
{
for (int i = 0; i < 4; i++)
{
num[i] = n % 10;
n /= 10;
}
}

int to_number(int num[])      //将num数组转换为数字
{
int sum = 0;
for (int i = 0; i < 4; i++)
{
sum = sum * 10 + num[i];   //哦,原来可以这样写啦
}
return sum;
}

int main() 
{     
freopen("C:\\Documents and Settings\\Administrator\\桌面\\data.txt", "r", stdin);
//MIN和MAX分别表示递增排序和递减排序后得到的最小值和最大值
int n, MIN, MAX;
scanf("%d", &n);
int num[5];
while (1)       //其实用do{} while()循环更好
{
to_array(n, num);     //将n转换为数组
sort(num, num + 4);   //递增排序
MIN = to_number(num);    //获取最小值
sort(num, num + 4, cmp);     //递减排序
MAX = to_number(num);    //获取最大值
n = MAX - MIN;        //得到下一个数
printf("%04d - %04d = %04d\n", MAX, MIN, n);
if (n == 0 || n == 6174)
break;            //下一个数若是0或6174,则退出
}
while (1);
return 0;
}

发表于 2017-09-04 19:57:09 回复(0)
20分。
#include "iostream"
#include "vector"
#include "string"
#include "cstring"
#include "cstdio"
#include "queue"
#include "stack"
#include "map"
#include "ctime"
#include <limits.h>
#include <algorithm>
using namespace std;


bool cmp(char s, char s2)
{
	return s > s2;
}

int main() {
	int resultNum;
	cin >> resultNum;
	string temp;
	int std = 1000, tempNum = resultNum;
	string s;
	for (int i = 0; i < 4; ++i)
	{
		s.push_back((tempNum / std + '0'));
		tempNum = tempNum % std;
		std /= 10;
	}
	string _increaseString = s, _decreaseString = s;
	sort(_increaseString.begin(), _increaseString.end());
	sort(_decreaseString.begin(), _decreaseString.end(), cmp);
	while (resultNum != 0 && resultNum != 6174)
	{
		sort(_increaseString.begin(), _increaseString.end());
		sort(_decreaseString.begin(), _decreaseString.end(), cmp);
		resultNum = stoi(_decreaseString) - stoi(_increaseString);
		string temp;
		int std=1000 ,tempNum = resultNum;
		for (int i = 0; i < 4; i++)
		{
			temp.push_back((tempNum / std + '0'));
			tempNum = tempNum % std;
			std /= 10;
		}
		cout << _decreaseString << " - " << _increaseString << " = " << temp << '\n';
		_increaseString = temp;
		_decreaseString = temp;
	}

}

发表于 2017-03-29 21:25:10 回复(0)
// 1069.cpp : 定义控制台应用程序的入口点。
//
#include <cstdio>
#include <iostream>
#include <vector>
#include <cstring>
#include <string>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <deque>
#include <cmath>
#include <cstdlib>
#include <functional>
using namespace std;

char num[5];

int main()
{
	int diff;
	scanf("%d", &diff);
	do {
		sprintf(num, "%04d", diff);
		sort(num, num + 4, greater<int>());
		int n1 = 0;
		for (int i = 0; i < 4; i++) n1 = 10 * n1 + num[i] - '0';
		sort(num, num + 4);
		int n2 = 0;
		for (int i = 0; i < 4; i++) n2 = 10 * n2 + num[i] - '0';
		diff = n1 - n2;

		printf("%04d - %04d = %04d\n", n1, n2, diff);
	} while (diff != 6174 && diff != 0);

    return 0;
}


发表于 2017-03-02 09:45:13 回复(0)

问题信息

难度:
23条回答 7699浏览

热门推荐

通过挑战的用户