zoukankan      html  css  js  c++  java
  • Stepping Number

    Problem

    A number is called as a stepping number if the adjacent digits are having a difference of 1. For eg. 8,343,545 are stepping numbers. While 890, 098 are not. The difference between a ‘9’ and ‘0’ should not be considered as1. Given start number(s) and an end number (e) your function should list out all the stepping numbers in the range including both the numbers s & e.

    Solution

    注意一下边界 0 和 9 就好

     1 public static List<Integer> stepNumber(int s, int e) {
     2     List<Integer> res = new ArrayList<Integer>();
     3     if(s > e) return res;
     4     
     5     int lens = (int) Math.floor(Math.log10(s) + 1);
     6     int lene = (int) Math.floor(Math.log10(e) + 1);
     7     
     8     for(int i=lens; i<=lene; i++) {    //number in the length range of s & e
     9         for(int j=1; j<10; j++) {    //start head from 1 to 9
    10             stepNumberHelper(res, s, e, i, j);
    11         }
    12     }
    13     
    14     return res;
    15 }
    16 
    17 public static void stepNumberHelper(List<Integer> res, int s, int e, int length, int num) {
    18     if(length-1 == 0) {
    19         if(num >= s && num <= e) {
    20             res.add(num);
    21         }
    22         return;
    23     }
    24     
    25     int lastDigit = num % 10;
    26     if(lastDigit == 0) {
    27         stepNumberHelper(res, s, e, length-1, num*10+1);
    28     }
    29     else if(lastDigit == 9) {
    30         stepNumberHelper(res, s, e, length-1, num*10+8);
    31     }
    32     else {
    33         stepNumberHelper(res, s, e, length-1, num*10+lastDigit+1);
    34         stepNumberHelper(res, s, e, length-1, num*10+lastDigit-1);
    35     }
    36 }
  • 相关阅读:
    java学生成绩管理系统
    7.19至7.25第八周学习情况
    8.12至8.18第七周学习情况
    8.5至8.11第六周学习情况
    7.29至8.4第五周学习情况
    《大道至简》读后感
    7.22至7.28第四周学习情况
    7.15至7.21第三周学习情况
    LeetCode 第三题:Longest Substring Without Repeating Characters
    哈希表(散列表)
  • 原文地址:https://www.cnblogs.com/superbo/p/4112121.html
Copyright © 2011-2022 走看看