您的位置:首页 > Web前端

剑指offer 32. 1到n整数中2出现的次数

2017-05-05 10:18 302 查看
//题目:从1到n个整数中输出2出现的次数
//解法1:同一每个数字中包含2的次数并相加
public class Main {

public static void main(String[] args) throws Exception {
System.out.println(get2Count(100));
}

public static int get2Count(int n){
int i = 1;
int result = 0;
while(i<=n){
result = result+getNum(i);
i++;
}
return result;
}

public static int getNum(int num){
int result = 0;
while(num != 0){
if(num%10 == 2){
result++;
}
num = num/10;
}
return result;
}

}

//解法2:按照数字位数出现的次数进行计算
public class Main {

public static void main(String[] args) throws Exception {
System.out.println(get2Count(100));
}

public static int get2Count(int n){
String str = String.valueOf(n);
return getNum(str);
}

public static int getNum(String str){
if(str == null || str.length() == 0){
return 0;
}
int length = str.length();
int first = str.charAt(0)-'0';
if(length == 1 && first>1){
return 1;
}
if(length == 1 && first<=1){
return 0;
}
int numFirst = 0;															//第一位可能出现2的次数和两种可能
if(first>2){
numFirst = (int)Math.pow(10,length-1);
}else if(first == 2){
numFirst = Integer.parseInt(str.substring(1))+1;
}
int numSecond = first*(length-1)*(int)Math.pow(10,length-2);				//剩余位在第一位不变的情况下可能出现2的次数,其实就是全排列
int numIter = getNum(str.substring(1));										//将第一位删除,迭代执行程序
return numFirst+numSecond+numIter;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: