您的位置:首页 > 其它

count the number of 1 in a decimal integer

2013-08-07 12:00 393 查看
#include <iostream>

using namespace std;

long count1sOfInteger(int num)
{
long res = 0;
int factor = 1;

long high, cur, low;
while(num / factor)
{
low = num - (num/factor)*factor;//num % factor;
cur = (num/factor) % 10;
high = (num/factor) / 10;

switch(cur)
{
case 0:
res += (high*factor);
break;
case 1:
res += (high*factor) + (low+1);
break;
default:
res += (high+1) * factor;
break;
}

factor *= 10;
}

return res;
}

int main()
{
int num;
while(cin >> num)
{
int count = count1sOfInteger(num);
cout << count << endl;
}

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