MENU

第八届蓝桥杯 Java B—— 取数位

March 17, 2019 • Read: 3339 • 算法阅读设置

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

对于题目中的测试数据,应该打印 5。

请仔细分析源码,并补充划线部分所缺少的代码

  • public class Main {
  • static int len(int x) {
  • if (x < 10)
  • return 1;
  • return len(x / 10) + 1;
  • }
  • // 取x的第k位数字
  • static int f(int x, int k) {
  • if (len(x) - k == 0)
  • return x % 10;
  • return f(x / 10, k); // 填空
  • }
  • public static void main(String[] args) {
  • int x = 23513;
  • System.out.println(f(x, 3));
  • }
  • }
Archives Tip
QR Code for this page
Tipping QR Code