2016.08.02 math(leetcode) 小结

math(leetcode) 小结

在leetcode中有些知识点(套路)

判断一个数是不是能被某些数整除,可以用 n%x == 0,循环除的话,就将while(n%x == 0)的循环条件设置判断整除(取余),然后除该数后在继续判断。

231.power of two(判断一个数是不是2的幂)

 1 class Solution {
 2 public:
 3     bool isPowerOfTwo(int n) {
 4         if(n == 0) return false;
 5         if(n == 1) return true;
 6         while(n % 2 == 0)
 7         {
 8             n = n / 2;
 9         }
10         return n ==1;
11     }
12 };

263.ugly number(判断一个数的整除因子的质数是不是只包括2,3,5)

 1 class Solution {
 2 public:
 3     bool isUgly(int num) {
 4         if(num <= 0) return false;
 5         if(num == 1) return true;
 6         
 7         while(num%2 == 0) num = num /2;     //能够被2整除
 8         while(num%3 == 0) num = num /3;     //不能被2整除,能够被3整除
 9         while(num%5 == 0) num = num /5;     //不能被2、3整除,能够被5整除
10         
11         return num == 1;    //判断num是否等于1,等于返回true,不能于1返回false
12     }
13 };

326.power of three (判断一个数是不是3的幂)

 1 class Solution {
 2 public:
 3     bool isPowerOfThree(int n) {
 4          if(n <= 0) return false;
 5          if(n == 1) return true;
 6          while(n % 3 == 0)
 7          {
 8              n = n /3;
 9          }
10          return n == 1;
11     }
12 };
原文地址:https://www.cnblogs.com/zhuzhu2016/p/5730017.html