java - 如何知道整数在另一个整数中的位置
问题描述
有没有办法找出一个整数是否出现在另一个整数中?例如,如果给定两个整数 A 和 B。整数 A 出现在位置 P 的整数 B 中,则应返回最左边的位置。
例如,53 出现在位置 2 的 1953786 中,因此该函数应返回 2。
解决方案
您可以使用indexOf
如下方法:
public static void main(String[] args){
int n1 = 53;
int n2 = 1953786;
System.out.println(getIndexOfAinB(n1,n2));
}
private static int getIndexOfAinB(int n1, int n2) {
String str1 = Integer.toString(n1);
String str2 = Integer.toString(n2);
return str2.indexOf(str1);
}