LeetCode--Power of Three、Integer Break、Count Numbers with Unique Digits、Valid Perfect Square

本文探讨了几个有趣的算法问题,包括判断一个数是否为3的幂次方,将整数拆分为多个数以最大化乘积,计算由独特数字组成的数的数量,以及判断一个数是否为完全平方数。通过具体实例和代码实现,展示了如何巧妙地解决这些数学问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

326. Power of Three

Given an integer, write a function to determine if it is a power of three.

给定一个整数,写一个函数来判断它是否是 3 的幂次方。

class Solution(object):
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n<1:
            return False
        while n%3==0:
            n/=3
        if n==1:
            return True
        else:
            return False

343. Integer Break

Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.

Example 1:

Input: 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.

Example 2:

Input: 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.

给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。

class Solution(object):
    def integerBreak(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n==2:
            return 1
        if n==3:
            return 2
        res=1
        while n>4:
            res*=3
            n-=3
        return res*n

357. Count Numbers with Unique Digits

Example:

Input: 2
Output: 91 
Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100, 
             excluding 11,22,33,44,55,66,77,88,99

思路:

  1. 如果n = 1,那么可以有10个数字不同(0~9)
  2. 如果n >= 2,那么第一位可以是1~9共9个数字,第二位可以是出去第一位的数字+0共9个数字,之后的每位数字都必须不能使用前面已经用过的数字所以依次递减。即9,9,8,7,…,1
  3. n位数字中由不同的数字构成的数字,是比它小的各位数字所能构成的该条件的数字求和。
class Solution(object):
    def countNumbersWithUniqueDigits(self, n):
        """
        :type n: int
        :rtype: int
        """
        nums=[9,9,8,7,6,5,4,3,2,1]
        ans,m=1,1
        for i in range(min(n,10)):
            m*=nums[i]
            ans+=m
        return ans

367. Valid Perfect Square

Given a positive integer num, write a function which returns True if num is a perfect square else False.

Note: Do not use any built-in library function such as sqrt.

Example 1:

Input: 16
Output: true

Example 2:

Input: 14
Output: false

给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。

class Solution(object):
    def isPerfectSquare(self, num):
        """
        :type num: int
        :rtype: bool
        """
        low=1
        high=num
        while low<=high:
            mid=(low+high)/2
            if mid*mid>num:
                high=mid-1
            elif mid*mid<num:
                low=mid+1
            else:
                return True
        return False

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值