2020年10月蓝桥杯原题寻找2020

这题比较简单,主要是以行,列,斜线的方式寻找2020的个数
注意的一点就是控制下标越界的情况
答案是16520

public class test4 {
    public static String readTxt(File file){
        String result ="";

            try {
                BufferedReader bread = new BufferedReader(new FileReader(file));//构造一个BuffrerdReader类读取文件
                String s = null;
                while ((s = bread.readLine())!=null){//一行一行读取,也可以一次性读取完
                    result+=s;//将读取的字符串连接成一串
                    //System.out.println(s);
                }
                bread.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;//返回读取的字符
    }
    
    public static void main(String args[]){

        File file = new File("D:/2020.txt");//创建文件类
        String s = readTxt(file);//调用读取文件方法
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();//输入N
        int [][] a = new int[n][n];
        int k = 0;//记录2020的总个数



        //将读取的字符以数字形式按n行n列排放
        for(int i = 0 ; i < n ; i ++){
            String ss = s.substring(i*n,(i+1)*n);
            System.out.println(ss);
            String[] sss = ss.split("");
            for(int j = 0 ; j < n ; j ++){
                a[i][j] = Integer.parseInt(sss[j]);
            }
        }


        //比较2020
        for(int i = 0 ; i < n ; i ++){
            for(int j = 0 ; j < n-3 ; j ++){

                //行
                int temp = a[i][j] * 1000 + a[i][j+1] * 100 + a[i][j+2] * 10 + a[i][j+3] ;
                if(temp == 2020){
                    k ++;
                }
                //列
                temp = a[j][i] * 1000 + a[j+1][i] * 100 + a[j+2][i] * 10 + a[j+3][i];
                if(temp == 2020){
                    k++;
                }
                //斜线
                if(i < n-3){
                    temp = a[i][j] *1000 + a[i+1][j+1] * 100 + a[i+2][j+2] * 10 + a[i+3][j+3];
                    if(temp == 2020){
                        k++;
                    }
                }
            }
        }

    System.out.println(k);


        
    }

}

这个查询方法不是我想出来的,附上原创文章

https://blog.csdn.net/Yh_yh_new_Yh/article/details/109144263?utm_source=app

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值