LeetCode每日一题(263. Ugly Number)

An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.

Given an integer n, return true if n is an ugly number.

Example 1:

Input: n = 6
Output: true

Explanation: 6 = 2 × 3

Example 2:

Input: n = 1
Output: true

Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.

Example 3:

Input: n = 14
Output: false

Explanation: 14 is not ugly since it includes the prime factor 7.

Constraints:

  • -231 <= n <= 231 - 1

突然发现不同语言对于相同的负数 mod 操作, 得到的结果是不同的, 比如同样是-11 % 7, 在 python 中是 3, 在 rust 中则是-4, 我倒是不怀疑两者的正确性, 只是觉得是表达方式不同而已, 但是为什么表达方式不一样, 这两种表达方式怎么相互转换, 这些是真不清楚, 然后去搜索相关问题, 发现 stackoverflow 上有个回答简单明了, 这里不做赘述, 原文地址粘在这里, 大家愿意去看的看一下吧


impl Solution {
    pub fn is_ugly(mut n: i32) -> bool {
        if n == 0 {
            return false;
        }
        while n < 0 {
            n += i32::MAX;
        }
        while n > 1 {
            if n % 2 == 0 {
                n /= 2;
                continue;
            }
            if n % 3 == 0 {
                n /= 3;
                continue;
            }
            if n % 5 == 0 {
                n /= 5;
                continue;
            }
            return false;
        }
        true
    }
}

你可能感兴趣的:(数据结构,算法,leetcode,算法,职场和发展)