在给定的间隔内查找以31开头和以21结尾的数字

本文关键字:开头 数字 结尾 查找 | 更新日期: 2023-09-27 17:53:16

我正在寻找一个函数(与整数/数学操作,而不是字符串),将确定输入数字是否以31开始,以21结束。

例如:

{341521, 513135, 434632, 312321, 315364, 312421}

函数应该返回312321和312421。

我还没有完成它,但这是我目前所做的(c#):

public bool IsValidId(int input)
{
    var result = input >= 310000 && input < 320000;
    if (result)
    {
        // Check for anything ending with 21, maybe something like
        // var endWith = (double) ((input / 21) / 100);
        // then check if endWith has decimal..
    }
    return result;
}

在给定的间隔内查找以31开头和以21结尾的数字

这可以通过使用startsWithendsWith来简单地使用字符串来实现,但是如果你根本不想使用字符串,你可以使用Math.log10Math.pow函数来查找数字中的数字。我本想解释这些函数的用法,但我的数学术语太生疏了,我肯定会失败得很惨。我注释了代码来解释变量的用法。

public static void main(String [] args) {
    int [] checks = new int[] { 341521, 513135, 434632, 312321, 315364, 312421 };
    for(int check : checks) {
        System.out.println(check + " " + startsWithEndsWith(check, 31, 21));
    }
}
public static boolean startsWithEndsWith(int value, int startWithNumber, int endsWIthNumber) {
    // get the number of digits for each of our inputs
    int numValueDigits = (int) Math.log10(value);
    int numStartsDigits = (int) Math.log10(startWithNumber);
    int numEndsDigits = (int) Math.log10(endsWIthNumber);
    // if the value doesnt have as many digits as either our starting or ending numbers then its impossible to be true
    if(numValueDigits < numStartsDigits || numValueDigits < numEndsDigits) {
        return false;
    }
    // for each of our startWithNumber digits check if the number in the value matches the corrisponding number in the startsWithNumber
    for(int i=0;i<=numStartsDigits;i++) {
        if(getDigitAt(value, numValueDigits-i) != getDigitAt(startWithNumber, numStartsDigits-i)) {
            return false;
        }
    }
    // for each of our endsWithNumber digits check if the number in the value matches the corrisponding number in the endsWithNumber
    for(int i=0;i<=numEndsDigits;i++) {
        if(getDigitAt(value, i) != getDigitAt(endsWIthNumber, i)) {
            return false;
        }
    }
    // nothing failed therefore its valid
    return true;
}
/**
 * returns the digit at the specified location, starting at 0 would be the 1's place. Returns 0 if the location is higher than the number
 * @param num
 * @param location 0<=location<=9
 * @return
 */
private static int getDigitAt(int num, int location) {
    // divide our number by 10^location to make the digit at the location
    // be in the 1's position, then modulus that by 10 to extract the digit
    return (int) (num/Math.pow(10, location)) % 10;
}

你可以用余数除以10^n/10^(n-1)得到一个数的第n位,然后取整数部分(~math.floor)

int((3123 % 10^4) / 10^3) = 3
int((3123 % 10^3) / 10^2) = 1
int((3123 % 10^2) / 10^1) = 2
int((3123 % 10^1) / 10^0) = 3

对所有数字进行循环,每个数字使用O(1)来检查它们是否满足条件:设C为当前数字

  1. c %100 == 21
  2. 让d =地板(日志(C) + 1),如果(d2的> = 0,,C/10^(d-2) == 31)

如果C满足这两个条件,那么它是31*21数之一

当然,为什么不直接使用string来检查C[0,1] == "31" &&C[镜头2,镜头1]== "21"?