美文网首页
[leetcode] Math

[leetcode] Math

作者: ccsexyz | 来源:发表于2016-06-29 01:31 被阅读0次
    • Palindrome Number
      最简单的思路是直接将数字转换为字符串然后翻转进行比较,也可以对通过对数字不断取余数再移进新的数字的方法实现.
    bool isPalindrome(int x) {
        if (x < 0) {
            return false;
        }
        int c = 0;
        int save_x = x;
        while (x) {
            c = c * 10 + x % 10;
            x /= 10;
        }
        return c == save_x;
    }
    
    • Move Zeros
      注意一个特点,非0数的最终位置肯定不会出现在初始位置的右边
    void moveZeroes(int* nums, int numsSize) {
        int nz = 0; // not zero 
        for(int i = 0; i < numsSize; i++) {
            if(nums[i] != 0) {
                if(i != nz) {
                    nums[nz] = nums[i];
                }
                nz++;
            }
        }
        for(int i = nz; i < numsSize; i++) {
            nums[i] = 0;
        }
    }
    
    • Trailing Zeroes
      题目要求求结果末尾的0的个数,本质上是求n!因数分解相乘后有多少对2*5,进一步等价于有多少个因子是5
    int trailingZeroes(int n) {
        int ret = 0;
        for (int i = 5; i <= n; i = i * 5) {
            ret += n / i;
        }
        return ret;
    }
    

    相关文章

      网友评论

          本文标题:[leetcode] Math

          本文链接:https://www.haomeiwen.com/subject/yfatjttx.html