[英]How to check every digit of a number is greater or equal than another number?
Every digit should be greater or equal than another. 每个数字都应大于或等于另一个数字。 If all digit are equal, return false.
如果所有数字均相等,则返回false。
Examples: 例子:
201 >= 200 true
200 >= 200 false
200 >= 101 false
210 >= 201 false
The ordinary way is constantly divide by 10, and then compare the remainder. 普通的方法是不断除以10,然后比较余数。
Here is the code in Java: 这是Java中的代码:
private boolean isScoreBetter(final int score, final int scoreToCompare) {
int a = score;
int b = scoreToCompare;
int betterCount = 0;
while (a > 0 && b > 0) {
int temp = a % 10 - b % 10;
if (temp < 0) {
return false;
}
if (temp > 0) {
betterCount++;
}
a /= 10;
b /= 10;
}
return betterCount > 0 && a >= b;
}
Is there a better way? 有没有更好的办法? Definition of "better":
“更好”的定义:
Constraint of the two numbers: 两个数字的约束:
Thank you for your reply. 谢谢您的回复。
str1 = '000'
str2 = '111'
all(a >= b for a, b in zip(str1, str2))
# False
all(a >= b for a, b in zip(str2, str1))
# True
If you don't want to convert the number to a string (as you said in your edit), there's still more than one way to do it. 如果您不想将数字转换为字符串(如您在编辑中所说),则还有多种方法可以实现。
You can write an iterator that give you the next digit: 您可以编写一个迭代器,为您提供下一位数字:
def next_digit(number):
while (number > 1):
yield number % 10
number = number // 10
Then you can map
over all values and use all
like in the other answer: 然后,你可以
map
在所有值,并使用all
像其他答案:
a = 201
b = 200
res = all(map(lambda d: d[0] >= d[1], zip(next_digit(a), next_digit(b))))
print(res) # True
Or you could use filter
and see if there are any digits that do not satisfy the condition: 或者,您可以使用
filter
,查看是否有不满足条件的数字:
res = filter(lambda d: d[0] < d[1], zip(next_digit(a), next_digit(b)))
print(res) # []
But, if you have numbers with a really large amount of digits, these approaches might be inefficient, because they go through all the digits anyway. 但是,如果您的数字中包含大量数字,则这些方法可能效率不高,因为它们始终会遍历所有数字。
You can write a rolled out for loop and optimize a bit by breaking out of it at the first digit that doesn't match your criteria. 您可以编写一个分期付款的for循环并通过在与您的条件不匹配的第一个数字处将其中断进行优化。
You can do that with an iterator, too: 您也可以使用迭代器来做到这一点:
def next_two_digits(a, b):
while (a > 1 and b > 1):
yield (a % 10, b % 10)
a = a // 10
b = b // 10
And you can either use it as the previous one: 您可以将其用作上一个:
res = all(map(lambda d: d[0] >= d[1], next_two_digits(a, b)))
print(res) # True
res = filter(lambda d: d[0] < d[1], next_two_digits(a, b))
print(res) # []
Or you can do the unrolled-loop thing: 或者,您可以执行展开循环操作:
matching = True
for d in next_two_digits(a, b):
if (d[0] < d[1]):
matching = False
break
print(matching)
Keep in mind that there is a constraint here on the fact that the two numbers need to have the same amount of digits. 请记住,这两个数字必须具有相同数量的数字,这是一个约束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.