2-4 1的数目


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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值