还望大家积极评论,说出自己的想法,这样大家互相促进。。。。
题目如下:
The 2020 is a number where index value is equal to number of times occurrence of index in number. for eg: for 2020
index(0)=2 (as 0 occured 2 times in 2020)
index(1)=0 (as 1 occured 0 times)
index(2)=2 (as 2 occured 2 times)
index(3)=0 (as 3 occured 0 times)
Now input given is a number, determine whether the given number posses property same as 2020 (given as example in above question)
因为时间紧张,我很快的写了一个算法,还有很多可以改进的地方,还请大家斧正。
java代码如下:
/**
* 因为如果 我们去求这个数的位数会比较费事,所以我们可以把这个数先转换成一个String,然后
* 利用字符查找的方法来解决这个问题。
*/
public static boolean numberCheck(int num){
String numStr = ""+num; //先把这个数字包装到字符串中,以方便用每个字符查找
if(numStr.length()>10){
return false; //显然如果这个数是十一位数或者更大,根本不能满足
}
//char[] numChars = numStr.toCharArray();
for(int i =0;i<numStr.length();i++){
int times = Integer.parseInt(numStr.substring(i,i+1)); //i在num出现的次数
int count =0;
for(int j = 0;j<numStr.length();j++){
if((String.valueOf(i).equals(String.valueOf(numStr.charAt(j))))){
++count;
}
}
if(times!=count){
return false;
}
}
return true;
}
请大家多多指下,把你的算法也贴出来大家互相学习。。~~