1049. Counting Ones

来源:互联网 发布:php项目开发视频 编辑:程序博客网 时间:2024/06/05 19:33

我实在编程之美上看的答案,把一个数分位讨论再相加,即把个位十位、、出现的1的个数各自加起来,不同的位的1的个数互不影响。难点就是一般大家不会想到这样分位进行讨论吧。

#include<iostream>using namespace std;int main(){    int n,cnt=0;    cin>>n;    for(int t,base=1;n/base;base*=10)    {        cnt+=base*(n/(10*base));        t=(n%(base*10))/base;        if(t==1)cnt+=n%base+1;        if(t>1)cnt+=base;    }    cout<<cnt;}


0 0
原创粉丝点击