第八届蓝桥杯省赛真题--取数位

版权声明:本文为博主原创文章,未经博主允许不得转载。

一、问题描述

  求1个整数的第k位数字有很多种方法。以下的方法就是一种。

 1 public class Main
 2 {
 3     static int len(int x){
 4         if(x<10) return 1;
 5         return len(x/10)+1;
 6     }
 7     
 8     // 取x的第k位数字
 9     static int f(int x, int k){
10         if(len(x)-k==0) return x%10;
11         return ______________________;  //填空
12     }
13     
14     public static void main(String[] args)
15     {
16         int x = 23513;
17         //System.out.println(len(x));
18         System.out.println(f(x,3));
19     }
20 }

  对于题目中的测试数据,应该打印5。请仔细分析源码,并补充划线部分所缺少的代码。注意:只提交缺失的代码,不要填写任何已有内容或说明性的文字。

二、题目类型:代码填空

三、解题思路及答案

  这道题做不出来的朋友别整蓝桥了(滑稽)。。。。

  当数字长度等于第K位时,直接取模取尾;当数字长度大于第K位时,要先用除去尾再取尾。

  答案:x/(int)Math.pow(10, len(x)-k)%10

四、反思与总结

static int len(int x){
        if(x<10) return 1;
        return len(x/10)+1;
}

  不得不说这个算数字长度的方法还挺好,反正要我算我首先想的是转字符串直接调用length()方法。。。。。思维太定式了哭唧唧

猜你喜欢

转载自www.cnblogs.com/crush-u-1214/p/10508446.html