zoukankan      html  css  js  c++  java
  • [LeetCode] Strobogrammatic Number III

    A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).

    Write a function to count the total strobogrammatic numbers that exist in the range of low <= num <= high.

    For example,
    Given low = "50", high = "100", return 3. Because 69, 88, and 96 are three strobogrammatic numbers.

    Note:
    Because the range might be a large number, the low and high numbers are represented as string.

     

     1 public class Solution {
     2     private int count = 0;
     3     public int strobogrammaticInRange(String low, String high) {
     4         find(low, high, "");
     5         find(low, high, "0");
     6         find(low, high, "1");
     7         find(low, high, "8");
     8         return count;
     9     }
    10     private void find(String low, String high, String s){
    11         //all possible strobogrammatic numbers that are needed to account for 
    12         //must have the length of [low.length(), high.length()]
    13         if(s.length() >= low.length() && s.length() <= high.length()){
    14             //ignore the numbers that have the same length with low but are 
    15             //smaller than low. Similarly, ignore the numbers that have the 
    16             //same length with high but are bigger than high
    17             if(s.length() == low.length() && s.compareTo(low) < 0 || 
    18                 s.length() == high.length() && s.compareTo(high) > 0){
    19                 return;
    20             }
    21             //ignore the cases where s.equals("0") == false && s.charAt(0) == '0'
    22             if(!(s.length() > 1 && s.charAt(0) == '0')){
    23                 count++;
    24             }
    25         }
    26         //recursion exit condition: if s.length() is already bigger than the 
    27         //upper bound length, then there is no need to keep searching, exit!
    28         else if(s.length() > high.length()){
    29             return;
    30         }
    31         find(low, high, "0" + s + "0");
    32         find(low, high, "1" + s + "1");
    33         find(low, high, "6" + s + "9");
    34         find(low, high, "8" + s + "8");
    35         find(low, high, "9" + s + "6");
    36     }
    37 }

     

     

    Related Problems

    Strobogrammatic Number II

  • 相关阅读:
    多线程篇七:通过Callable和Future获取线程池中单个务完成后的结果
    多线程篇六:线程池
    微服务学习和认识
    多线程篇五:多个线程访问共享对象和数据的方式
    多线程篇四:ThreadLocal实现线程范围内变量共享
    多线程篇三:线程同步
    多线程篇二:定时任务
    多线程篇一:传统线程实现方式
    Jms学习篇二:ActiveMQ
    04-运算符
  • 原文地址:https://www.cnblogs.com/lz87/p/7038891.html
Copyright © 2011-2022 走看看