蓝桥杯历届试题 带分数

问题描述

100 可以表示为带分数的形式:100 = 3 + 69258 / 714。

还可以表示为:100 = 82 + 3546 / 197。

注意特征:带分数中,数字1~9分别出现且只出现一次(不包含0)。

类似这样的带分数,100 有 11 种表示法。

输入格式

从标准输入读入一个正整数N (N<1000*1000)

输出格式

程序输出该数字用数码1~9不重复不遗漏地组成带分数表示的全部种数。

注意:不要求输出每个表示,只统计有多少表示法!

样例输入1

100

样例输出1

11

样例输入2

105

样例输出2

6

分析

可以通过全排列的方式,把1-9的排列方式全部展开,有关全排列的知识如下:

https://blog.csdn.net/a429367172/article/details/88621642

然后通过循环判断+号和/号的位置,将他们分成x,a,b三个数,然后判断x + a /b == num,需要注意,a/b要能整除才行,因为用整形存储会出现丢弃小数位的情况。代码如下:


import java.util.Scanner;
import java.util.*;

public class Main {
	private static long num;
	private static int len;
	private static long count = 0;
	
	public static long toLong(int []arr, int start, int end) {
		long res = 0;
		for(int i = start; i <= end; i++) {
			res = res * 10 + arr[i];
		}
		return res;
	}
	
	public static long toLong(String num) {
		long res = 0;
		for(int i = 0; i < num.length(); i++) {
			res = res * 10 + num.charAt(i) - '0';
		}
		return res;
	}
	
	public static void swap(int []arr, int i, int j) {
		int tmp = arr[i];
		arr[i] = arr[j];
		arr[j] = tmp;
	}
	
	public static void fullSortSearch(int []arr, int start, int end)
	{
		if(start == end) {
			for(int i = 0; i < len; i++) {/*满足x + a/b == num*/
				long x = toLong(arr, 0, i);
				if(x > num)
					break;
				for(int j = i + 1; j < arr.length-1; j++) {
					long a = toLong(arr, i+1, j);
					long b = toLong(arr, j+1, arr.length-1);
					if(a % b != 0)
						continue;
					if(x + a / b == num) {
//						System.out.println(x + " " + a + " " + b);
						count++;
					}
				}
			}
		}
		for(int i = start; i <= end; i++)
		{
			swap(arr,start,i);
			fullSortSearch(arr,start+1,end);
			swap(arr,i,start);
		}
	}
	
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int []arr = {1,2,3,4,5,6,7,8,9};
        String n = scan.next();
        
        len = n.length();
        num = toLong(n);
        
        fullSortSearch(arr, 0, arr.length-1);
        System.out.println(count);
    }

}

猜你喜欢

转载自blog.csdn.net/a429367172/article/details/88698130