738. Monotone Increasing Digits

本文介绍了一种算法,用于找到小于或等于给定非负整数N的最大单调递增数。通过从个位开始检查并调整数字,确保高位不大于低位,从而实现数字的单调递增。

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

Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits.

(Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.)

Example 1:

Input: N = 10
Output: 9


**Example 2:**
Input: N = 1234
Output: 1234


**Example 3:**
Input: N = 332
Output: 299

Note: N is an integer in the range [0, 10^9].

Hint:
要找小于或等于一个数的,最大的单调递增数(高位不大于低位),显然是个贪心问题。
我们知道,尽量保证高位不减少或降幅尽可能小,则数字越大。
我们应该去首先考虑去修改低位,使低位变大。
因此从个位开始,如果低位小于其前一个高位,将这个高位-1,而使低位变成最大的‘9’。

class Solution {
public:
    int monotoneIncreasingDigits(int N) {
        stringstream ss;
        ss << N;
        string num;
        ss >> num;
        int k = num.size();
        for (int i = num.size()-1; i > 0; i--) {
            if (num[i] < num[i-1]) {
                k = i;
                num[i-1] -= 1;
            }
        }
        for (int i = k; i < num.size(); i++) {
            num[i] = '9';
        }
        ss.clear();
        ss << num;
        ss >> N;
        return N;
    }
};
### 单调访问结构的概念 在密码学和安全系统中,单调访问结构是一种用于定义授权集合的方法。这种结构的特点在于如果一个用户集合作为成员可以满足访问条件,则任何包含该集合的更大集合也能够满足相同的访问条件[^1]。 具体来说,在属性基加密(Attribute-Based Encryption, ABE)和其他基于策略的安全机制中,单调访问结构允许设计者指定哪些用户的组合有权解密特定的信息或执行某些操作。当某个小组具备足够的属性来解锁资源时,那么任何一个拥有这些属性加上额外其他属性的大组同样有权限这样做。 ### 应用实例 #### 属性基加密 (ABE) 在一个典型的场景下,假设一家公司希望保护其内部文件只被具有适当职位级别的员工查看。通过构建合适的单调访问树形图,管理员可以根据职务等级分配不同的权重给各个部门经理、主管以及普通职员等角色标签。只要某位雇员所持有的全部角色标签总权重大于等于预设阈值,即认为此人属于合法使用者群体之一;而一旦确认这一点成立之后,即使再增加更多低级别身份也不会改变这一事实——这正是体现了上述提到过的“单增性质”。 ```python def check_access(user_attributes, required_structure): """ Check if the user's attributes satisfy a monotone access structure. :param user_attributes: Set of attributes possessed by the user :param required_structure: Monotone access structure defined as set of sets :return: True if access is granted, False otherwise """ for subset in required_structure: if subset.issubset(user_attributes): # If any subset matches or is contained within user's attributes return True return False ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值