从右边开始寻找整数的第k位
从右边开始寻找整数的第k位
Implement match_k
, which takes in an integer k
and returns a function that takes in a variable x
and returns True
if all the digits in x
that are k
apart are the same.
For example, match_k(2)
returns a one argument function that takes in x
and checks if digits that are 2 away in x
are the same.
match_k(2)(1010)
has the value of x = 1010
and digits 1, 0, 1, 0 going from left to right. 1 == 1
and 0 == 0
, so the match_k(2)(1010)
results in True
.
match_k(2)(2010)
has the value of x = 2010
and digits 2, 0, 1, 0 going from left to right. 2 != 1
and 0 == 0
, so the match_k(2)(2010)
results in False
.
Important: You may not use strings or indexing for this problem.
Floor dividing by powers of 10 gets rid of the rightmost digits.
def match_k(k): """Returns a function that checks if digits k apart match. >>> match_k(2)(1010) True >>> match_k(2)(2010) False >>> match_k(1)(1010) False >>> match_k(1)(1) True >>> match_k(1)(2111111111111111) False >>> match_k(3)(123123) True >>> match_k(2)(123123) False """ def check(x): while x // (10 ** k) > 0: if (x % 10) != (x // (10 ** k)) % 10: return False x //= 10 return True return check
分析:
- 判断最后一位与右边数第k位数字是否相同:
(x % 10) != (x // (10 ** k)) % 10
- 如果不相同,则这个数肯定不符合题目要求,直接返回
False
- 如果相同,则将比较位置转为左手边的下一个数字:
x //= 10
本文作者:上山砍大树
本文链接:https://www.cnblogs.com/shangshankandashu/p/18027058
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!