Created
September 21, 2014 07:03
-
-
Save fuzhengwei/d915a77fdc9ccb407a55 to your computer and use it in GitHub Desktop.
给出一个整数,计算从0到这个整数(包含这个整数)1出现的次数 例如,给出整数:13 -》 0,1,2,3,4,5,6,7,8,9,10,11,12,13 数字1出现了7次,返回6。如果普通的写出来这个函数很随意, 挑战在于-》不要遍历所有的数 (能计算到2千万,计算机1秒内完成计算)看你是否可以做出来?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class XiaoFuNumberGetOne { | |
/** | |
* @param args | |
* | |
*/ | |
public static void main(String[] args) { | |
// TODO Auto-generated method stub | |
int num = 112,saveNum = 1,countNum = 0,lastNum=0,numCopy = num; | |
while(num!=0) | |
{ | |
lastNum = num%10; | |
num/=10; | |
if(lastNum == 0){ | |
countNum +=(num)*saveNum; | |
}else if(lastNum == 1){ | |
countNum += num * saveNum + numCopy%(saveNum) + 1;//对于有1的处理 看表 放可理解(对于不是个位的数从后面开始获得1的数量) | |
}else{ | |
countNum +=(num+1)*saveNum; | |
} | |
saveNum*=10; | |
} | |
System.out.println(countNum); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment