public class ch2_4 {
static long f (long n){
long iCount=0;
for(long i=0;i<=n;i++){
iCount += Count1InAInteger(i);
}
return iCount;
}
static long Count1InAInteger(long n){
long iNum=0;
while(n!=0){
iNum += ( n%10==1 ) ? 1 : 0;
n /= 10;
}
return iNum;
}
static long Sum1s(long n){
long iCount=0;
long iFactor=1;
long iLowerNum=0;
long iCurrNum=0;
long iHigherNum=0;
while( n / iFactor != 0 ){
iLowerNum = n - ( n / iFactor ) * iFactor;
iCurrNum = ( n / iFactor ) % 10;
iHigherNum = n / ( iFactor * 10 );
switch(Integer.parseInt(String.valueOf(iCurrNum))){
case 0:
iCount += iHigherNum*iFactor;
break;
case 1:
iCount += iHigherNum*iFactor + iLowerNum +1;
break;
default:
iCount += ( iHigherNum+1 )*iFactor;
break;
}
iFactor *= 10;
}
return iCount;
}
//Cannot make a static reference to the non-static method f(long) from the type ch2_4
public static void main(String args[]){
long n=1111111110;
System.out.println("1到n之间出现“1”个数f(n) :"+f(n));
System.out.println("1到n之间出现“1”个数Sum1s(n) :"+Sum1s(n));
}
}
注意:1、switch()括号中不能是long型。把long转化为int 。
//Cannot switch on a value of type long. Only convertible int values, strings or enum variables are permitted
①调用intValue()方法: switch(new Long(iCurrNum).intValue())
②先把long转换成字符串String,然后在转成Integer : switch(Integer.parseInt(String.valueOf(iCurrNum))
③强制类型转换 (int)iCurrNum