Every day a Leetcode
题目来源:2806. 取整购买后的账户余额
解法1:数学
题目要求为将 purchaseAmount 四舍五入到最近的 10 的倍数作为 roundedAmount,计算 100−roundedAmount 的值并返回。
分类讨论即可。
代码:
/** @lc app=leetcode.cn id=2806 lang=cpp** [2806] 取整购买后的账户余额*/// @lc code=start
class Solution
{
public:int accountBalanceAfterPurchase(int purchaseAmount){int roundedAmount;if (purchaseAmount % 10 < 5)roundedAmount = purchaseAmount - purchaseAmount % 10;else if (purchaseAmount % 10 > 5)roundedAmount = purchaseAmount + 10 - purchaseAmount % 10;elseroundedAmount = purchaseAmount + 5;return 100 - roundedAmount;}
};
// @lc code=end
one-line code:
// one-line codeclass Solution
{
public:int accountBalanceAfterPurchase(int purchaseAmount){return 100 - (purchaseAmount + 5) / 10 * 10;}
};
结果:
复杂度分析:
时间复杂度:O(1)。
空间复杂度:O(1)。