LeetCode 题解工作台

取整购买后的账户余额

一开始,你的银行账户里有 100 块钱。 给你一个整数 purchaseAmount ,它表示你在一次购买中愿意支出的金额。 在一个商店里,你进行一次购买,实际支出的金额会向 最近 的 10 的 倍数 取整。换句话说,你实际会支付一个 非负 金额 roundedAmount ,满足 roundedA…

category

1

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·driven

bolt

答案摘要

我们在 $[0, 100]$ 的范围内枚举所有的 的倍数,然后找到与 `purchaseAmount` 最接近的那个数,记为 ,那么答案就是 $100 - x$。 时间复杂度 ,空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

一开始,你的银行账户里有 100 块钱。

给你一个整数purchaseAmount ,它表示你在一次购买中愿意支出的金额。

在一个商店里,你进行一次购买,实际支出的金额会向 最近 的 10 的 倍数 取整。换句话说,你实际会支付一个 非负 金额 roundedAmount ,满足 roundedAmount 是 10 的倍数且 abs(roundedAmount - purchaseAmount) 的值 最小 。

如果存在多于一个最接近的 10 的倍数,较大的倍数 是你的实际支出金额。

请你返回一个整数,表示你在愿意支出金额为 purchaseAmount 块钱的前提下,购买之后剩下的余额。

注意: 0 也是 10 的倍数。

 

示例 1:

输入:purchaseAmount = 9
输出:90
解释:这个例子中,最接近 9 的 10 的倍数是 10 。所以你的账户余额为 100 - 10 = 90 。

示例 2:

输入:purchaseAmount = 15
输出:80
解释:这个例子中,有 2 个最接近 15 的 10 的倍数:10 和 20,较大的数 20 是你的实际开销。
所以你的账户余额为 100 - 20 = 80 。

 

提示:

  • 0 <= purchaseAmount <= 100
lightbulb

解题思路

方法一:枚举 + 模拟

我们在 [0,100][0, 100] 的范围内枚举所有的 1010 的倍数,然后找到与 purchaseAmount 最接近的那个数,记为 xx,那么答案就是 100x100 - x

时间复杂度 O(1)O(1),空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
class Solution:
    def accountBalanceAfterPurchase(self, purchaseAmount: int) -> int:
        diff, x = 100, 0
        for y in range(100, -1, -10):
            if (t := abs(y - purchaseAmount)) < diff:
                diff = t
                x = y
        return 100 - x
speed

复杂度分析

指标
时间complexity is O(1) because the operations consist only of rounding the number and performing a subtraction, both constant-time operations. The space complexity is O(1) as well since no additional data structures are required.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Can the candidate clearly explain the rounding concept?

  • question_mark

    Does the candidate handle all edge cases correctly?

  • question_mark

    Is the candidate able to recognize the simplicity of the solution and not overcomplicate the problem?

warning

常见陷阱

外企场景
  • error

    Failing to round correctly, especially for values like 5 or 95 that are at the rounding threshold.

  • error

    Overcomplicating the solution by using unnecessary loops or conditional structures.

  • error

    Not correctly handling the boundary cases such as 0 or 100.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Modify the problem to work with a different starting balance, such as 50 dollars, and adapt the solution accordingly.

  • arrow_right_alt

    Implement a similar solution where the rounding is done to a multiple of 5 instead of 10.

  • arrow_right_alt

    Extend the problem by adding a tax rate that must be deducted before rounding the purchase amount.

help

常见问题

外企场景

取整购买后的账户余额题解:数学·driven | LeetCode #2806 简单