1. 程式人生 > 其它 >力扣_數學

力扣_數學

Fizz Buzz

//迴圈判斷1~n是否是3和5的倍數 class Solution {     public List<StringfizzBuzz(int n) {         //設定返回的字串         List<Stringstr = new ArrayList<String>();         //迴圈判斷1~n是否是3和5的倍數         for(int i = 1;i <= n;i++){             if((i % 3 == 0) && (i % 5 == 0)){                 str.add("FizzBuzz");
            }else if(i % 3 == 0){                 str.add("Fizz");             }else if(i % 5 == 0){                 str.add("Buzz");             }else{                 str.add(Integer.toString(i));             }         }         return str;     } }    

計數質數

//超出時間限制 // //質數的判斷是,如果有任意一個比其小的數大於等於2(2除外)能夠做餘數為0,那麼這個數就不是質數
// class Solution { //     public int countPrimes(int n) { //         //記錄有多少個質數 //         int time = 1; //         if(n == 0 || n == 1 || n == 2){ //             return 0; //         } //         for(int i = 3;i < n;i++){ //             time++; //             for(int j = 2;j < i;j++){ //                 if(i % j == 0){
//                     time--; //                     break; //                 } //             } //         } //         return time; //     } // }
//因為質子是某個數的倍數,2、3等肯定是最小倍的質數,那麼它們的倍數一定都不是質數 //那麼可以從前往後捋,將其設定成可以做餘數的  class Solution {      public int countPrimes(int n) {         //消除特殊情況         if(n == 0 || n == 1 || n == 2){             return 0;         }         //設定陣列用於判斷是否為質數         int[] pd = new int[n+1];         //假設都為質數         Arrays.fill(pd,1);         //設質數的個數         int rev = 0;         for(int i = 2;i < n;i++){             if(pd[i] == 1){                 ++rev;                  if((long)i*i < n){                     for(int j = i * i;j < n;j = j+i){                         pd[j] = 0;                     }                 }             }         }         return rev;     } }  

 

3的冪

//可以不斷的除以三,判斷最後的值是否為1,過程中也要判斷是否能夠除餘3,不然Integer型別也會想其轉化為整數 class Solution {     public boolean isPowerOfThree(int n) {         while(n != 0 && n % 3 == 0){             n = n/3;         }         return n == 1;     } }    

羅馬數字轉整數

class Solution {     //後面一個是對應的要取出的資料     Map<Character,Integervalue = new HashMap<Character,Integer>(){{         put('I',1);         put('V',5);         put('X',10);         put('L',50);         put('C',100);         put('D',500);         put('M',1000);     }};     public int romanToInt(String s) {         //求字串的長度         int n = s.length();         //返回的總值         int rev = 0;         for(int i = 0;i < n;i++){             //用於取value圖中的資料             int temp = value.get(s.charAt(i));             //最後一個數據不用判斷,不然後出界             if(i < n-1 && temp < value.get(s.charAt(i+1))){                 rev = rev - temp;             }else{                 rev = rev + temp;             }         }         return rev;     } }