2015年11月4日星期三

Leetcode 246 Strobogrammatic Number

A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Write a function to determine if a number is strobogrammatic. The number is represented as a string.
For example, the numbers "69", "88", and "818" are all strobogrammatic.
Solution 1: two pointer
 public class Solution {  
   public boolean isStrobogrammatic(String num) {  
     int i=0, j=num.length()-1;  
     while (i<=j) {  
       if (!isStrob(num.charAt(i++),num.charAt(j--))) return false;  
     }  
     return true;  
   }  
   private boolean isStrob(char a, char b) {  
     if (a=='0') return b=='0';  
     if (a=='1') return b=='1';  
     if (a=='8') return b=='8';  
     if (a=='6') return b=='9';  
     if (a=='9') return b=='6';  
     return false;  
   }  
 }  

没有评论:

发表评论