7.22 第一次做,无法 AC,考虑大数的情况有点难想!看面试好像也出的不多!先跳过!

题目描述


原题链接:https://leetcode-cn.com/problems/da-yin-cong-1dao-zui-da-de-nwei-shu-lcof/

解题思路一:不考虑大数(面试可能不出,肯定得考虑大数)


K 神题解:https://leetcode-cn.com/problems/da-yin-cong-1dao-zui-da-de-nwei-shu-lcof/solution/

  1. class Solution {
  2. public int[] printNumbers(int n) {
  3. int end = (int)Math.pow(10, n) - 1; // 关键
  4. int[] res = new int[end];
  5. for(int i = 0; i < end; i++) {
  6. res[i] = i + 1;
  7. }
  8. return res;
  9. }
  10. }

解题思路二:考虑大数(有点难!先跳过!)


  • 卧槽,有点难!先跳过!

  • 考虑大数时,返回值得为 String,int 类型会越界!

  • K 神有个写错了:

  • image.png
    1. class Solution {
    2. StringBuilder res;
    3. int nine = 0, start, n; // nine: 遍历了多少次9的个数,start: 取值的左边界,保证将左边的0忽略掉,n: 位数
    4. char[] num, loop = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    5. public String printNumbers(int n) {
    6. this.n = n;
    7. res = new StringBuilder();
    8. num = new char[n];
    9. start = n - 1;
    10. dfs(0);
    11. res.deleteCharAt(res.length() - 1);
    12. return res.toString();
    13. }
    14. void dfs(int x) {
    15. if(x == n) {
    16. String s = String.valueOf(num).substring(start); // substring 也可以传一个参数,表示从此开始
    17. if(!s.equals("0")) res.append(s + ",");
    18. if(n - start == nine) start--; // 009、099的时候会执行
    19. return;
    20. }
    21. for(char i : loop) {
    22. if(i == '9') nine++;
    23. num[x] = i;
    24. dfs(x + 1);
    25. }
    26. nine--; // 进位了,所以 9 消失了
    27. }
    28. }