233 - Number of Digit One

本文深入探讨了如何通过优化算法提高数位计数任务的效率,从简单遍历法出发,逐步引入并解析了基于数学规律的高效解法。通过实例演示和代码实现,读者可以掌握数位计数背后的思考逻辑和关键步骤,从而提升解决类似问题的能力。

Number of Digit One

 Total Accepted: 307 Total Submissions: 1853

Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.

For example:
Given n = 13,
Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.


两经波折,一开始没想过会有大数的效率问题,后来发现,哦,原来考察的是找规律。

一开始的超时,最简单的解法:

        int countDigitOne(int n) {
                int sum = 0;
                for(int i = 1; i <= n; i++)
                        sum += count(i);
                return sum;
        }

        int count(int num) {
                int c = 0;
                while( num != 0 ) {
                        if(num % 10 == 1)
                                c++;
                        num = num / 10;
                }
                return c;
        }


超时后,参照了其他人的解法,努力去理解公式:

 ones += (a + 8) / 10 * m + (a % 10 == 1) * (b + 1);
发现,我的思路不对,肯定不能遍历所有比 n 小的数字啊,这样太慢了,因为是有规律可循的。

但是理解上述公式还是很困难的,我现在能够理解了,是经过自己拿数字去对应公式,比如3456这个数,利用这个公式去推导每一位可能为1的所有比该数小的数字个数的总和。

慢慢的理解,就积累了一道这样找规律的题目。另外,注意 a 和 b 要为 long型(这是细节)。

        int countDigitOne(int n) {
                int ones = 0;
                for(long m = 1; m <= n; m *= 10) {
                        long a = n / m;
                        long b = n % m;
                        ones += (a + 8) / 10 * m + (a % 10 == 1) * (b + 1);
                }
                return ones;
        }


[D] format -- Set variables' output format (View complete PDF manual entry) Syntax Set formats format varlist %fmt format %fmt varlist Set style of decimal point set dp {comma|period} [, permanently] Display long formats format [varlist] where %fmt can be a numerical, date, business calendar, or string format. Numerical %fmt Description Example ------------------------------------------------------- right-justified %#.#g general %9.0g %#.#f fixed %9.2f %#.#e exponential %10.7e %21x hexadecimal %21x %16H binary, hilo %16H %16L binary, lohi %16L %8H binary, hilo %8H %8L binary, lohi %8L right-justified with commas %#.#gc general %9.0gc %#.#fc fixed %9.2fc right-justified with leading zeros %0#.#f fixed %09.2f left-justified %-#.#g general %-9.0g %-#.#f fixed %-9.2f %-#.#e exponential %-10.7e left-justified with commas %-#.#gc general %-9.0gc %-#.#fc fixed %-9.2fc ------------------------------------------------------- You may substitute comma (,) for period (.) in any of the above formats to make comma the decimal point. In %9,2fc, 1000.03 is 1.000,03. Or you can set dp comma. date %fmt Description Example ------------------------------------------------------- right-justified %tc date/time %tc %tC date/time %tC %td date %td %tw week %tw %tm month %tm %tq quarter %tq %th half-year %th %ty year %ty %tg generic %tg left-justified %-tc date/time %-tc %-tC date/time %-tC %-td date %-td etc. ------------------------------------------------------- There are many variations allowed. See [D] Datetime display formats. business calendar %fmt Description Example ------------------------------------------------------- %tbcalname a business calendar %tbsimple [:datetime-specifiers] defined in calname.stbcal ------------------------------------------------------- See [D] Datetime business calendars. string %fmt Description Example ------------------------------------------------------- right-justified %#s string %15s left-justified %-#s string %-20s centered %~#s string %~12s ------------------------------------------------------- The centered format is for use with display only. Menu Data > Variables Manager Description format varlist %fmt and format %fmt varlist are the same commands. They set the display format associated with the variables specified. The default formats are a function of the type of the variable: byte %8.0g int %8.0g long %12.0g float %9.0g double %10.0g str# %#s strL %9s set dp sets the symbol that Stata uses to represent the decimal point. The default is period, meaning that one and a half is displayed as 1.5. format [varlist] displays the current formats associated with the variables. format by itself lists all variables that have formats too long to be listed in their entirety by describe. format varlist lists the formats for the specified variables regardless of their length. format * lists the formats for all the variables. Links to PDF documentation Quick start Remarks and examples The above sections are not included in this help file. Option permanently specifies that, in addition to making the change right now, the dp setting be remembered and become the default setting when you invoke Stata. Remarks Remarks are presented under the following headings: The %f format The %fc format The %g format The %gc format The %e format The %21x format The %16H and %16L formats The %8H and %8L formats The %t format The %s format Examples Video example The %f format In %w.df, w is the total output width, including sign and decimal point, and d is the number of digits to appear to the right of the decimal point. The result is right-justified. The number 5.139 in %12.2f format displays as ----+----1-- 5.14 When d==0, the decimal point is not displayed. The number 5.14 in %12.0f format displays as ----+----1-- 5 %-w.df works the same way, except that the output is left-justified in the field. The number 5.139 in %-12.2f displays as ----+----1-- 5.14 The %fc format %w.dfc works like %w.df except that commas are inserted to make larger numbers more readable. w records the total width of the result, including commas. The number 5.139 in %12.2fc format displays as ----+----1-- 5.14 The number 5203.139 in %12.2fc format displays as ----+----1-- 5,203.14 As with %f, if d==0, the decimal point is not displayed. The number 5203.139 in %12.0fc format displays as ----+----1-- 5,203 As with %f, a minus sign may be inserted to left justify the output. The number 5203.139 in %-12.0fc format displays as ----+----1-- 5,203 The %g format In %w.dg, w is the overall width, and d is usually specified as 0, which leaves up to the format the number of digits to be displayed to the right of the decimal point. If d!=0 is specified, then not more than d digits will be displayed. As with %f, a minus sign may be inserted to left-justify results. %g differs from %f in that (1) it decides how many digits to display to the right of the decimal point, and (2) it will switch to a %e format if the number is too large or too small. The number 5.139 in %12.0g format displays as ----+----1-- 5.139 The number 5231371222.139 in %12.0g format displays as ----+----1-- 5231371222 The number 52313712223.139 displays as ----+----1-- 5.23137e+10 The number 0.0000029394 displays as ----+----1-- 2.93940e-06 The %gc format %w.dgc is %w.dg, with commas. It works in the same way as the %g and %fc formats. The %e format %w.de displays numeric values in exponential format. w records the width of the format. d records the number of digits to be shown after the decimal place. w should be greater than or equal to d+7 or, if 3-digit exponents are expected, d+8. The number 5.139 in %12.4e format is ----+----1-- 5.1390e+00 The number 5.139*10^220 is ----+----1-- 5.1390e+220 The %21x format The %21x format is for those, typically programmers, who wish to analyze routines for numerical roundoff error. There is no better way to look at numbers than how the computer actually records them. The number 5.139 in %21x format is ----+----1----+----2- +1.48e5604189375X+002 The number 5.125 is ----+----1----+----2- +1.4800000000000X+002 Reported is a signed, base-16 number with base-16 point, the letter X, and a signed, 3-digit base-16 integer. Call the two numbers f and e. The interpretation is f*2^e. The %16H and %16L formats The %16H and %16L formats show the value in the IEEE floating point, double-precision form. %16H shows the value in most-significant-byte-first (hilo) form. %16L shows the number in least-significant-byte-first (lohi) form. The number 5.139 in %16H is ----+----1----+- 40148e5604189375 The number 5.139 in %16L is ----+----1----+- 75931804568e1440 The format is sometimes used by programmers who are simultaneously studying a hexadecimal dump of a binary file. The %8H and %8L formats %8H and %8L are similar to %16H and %16L but show the number in IEEE single-precision form. The number 5.139 in %8H is ----+--- 40a472b0 The number 5.139 in %8L is ----+--- b072a440 The %t format The %t format displays numerical variables as dates and times. See [D] Datetime display formats. The %s format The %ws format displays a string in a right-justified field of width w. %-ws displays the string left-justified. "Mary Smith" in %16s format is ----+----1----+- Mary Smith "Mary Smith" in %-16s format is ----+----1----+- Mary Smith In addition, in some contexts, particularly display (see [P] display), %~ws is allowed, which centers the string. "Mary Smith" in %~16s format is ----+----1----+- Mary Smith Examples Four values displayed in different numeric display formats +---------------------------------------------------------------------+ | %9.0g %9.0gc %9.2f %9.2fc %-9.0g %09.2f %9.2e | |---------------------------------------------------------------------| | 12345 12,345 12345.00 12,345.00 12345 012345.00 1.23e+04 | | 37.916 37.916 37.92 37.92 37.916 000037.92 3.79e+01 | | 3567890 3567890 3.57e+06 3.57e+06 3567890 3.57e+06 3.57e+06 | | .9165 .9165 0.92 0.92 .9165 000000.92 9.16e-01 | +---------------------------------------------------------------------+ Left-aligned and right-aligned string display formats +-------------------------------+ | %-17s %17s | |-------------------------------| | AMC Concord AMC Concord | | AMC Pacer AMC Pacer | | AMC Spirit AMC Spirit | | Buick Century Buick Century | | Buick Opel Buick Opel | +-------------------------------+ ---------------------------------------------------------------------------- Setup . webuse census10 Describe the data . describe List some of the data . list in 1/8 Left-align the state variable . format state %-14s List the result . list in 1/8 Left-align region, a numeric variable with attached value label . format region %-8.0g List the result . list in 1/8 Insert commas in the variable pop . format pop %12.0gc List the result . list in 1/8 Vertically align the decimal points in medage . format medage %8.1f List the result . list in 1/8 ---------------------------------------------------------------------------- Setup . webuse fmtxmpl, clear List some of the data . list empid in 83/87 Attach leading zeros to empid values . format empid %05.0f List the result . list empid in 83/87 ---------------------------------------------------------------------------- Setup . webuse fmtxmpl2, clear Display the formats of the three date variables . format hiredate login logout Attach a date format to login and logout . format login logout %tcDDmonCCYY_HH:MM:SS.ss List the result . list login logout in 1/5 Attach a date format to the hiredate variable . format hiredate %td List the result . list hiredate in 1/5 Attach a different date format to the hiredate variable . format hiredate %tdDD/NN/CCYY List the result . list hiredate in 1/5 Display the current formats for all variables using describe . describe Display the formats for the variables whose display format is too long to show in the describe output . format ---------------------------------------------------------------------------- Setup . webuse census10, clear Attach a European format to the variables pop and medage . format pop %12,0gc (note the comma) . format medage %9,2gc List the result . list in 1/8 Remove the European format from variables pop and medage . format pop %12.0gc (back to period for the decimal point) . format medage %9.2gc Change the setting for the decimal point to comma . set dp comma Perform a one-way tabulation . tabulate region [fw=pop] Restore period as the setting for the decimal point . set dp period ---------------------------------------------------------------------------- Video example How to change the display format of a variable . coefplot dyn_reg, level(90) baselevels keep(pre4 pre3 pre2 current post1 post2) co > eflabels(pre4="-4" pre3="-3" pre2="-2" current="0" post1="1" post2="2") yline(0, l > color(black) lwidth(medium)) ylabel(-0.06(0.03)0.09, labsize(vsmall) angle(0) fmt( > %10.3f)) xlabel(, labsize(vsmall)) xtitle("政策时点", size(small)) ytitle("对薪酬 > 差距的边际效应", size(small)) addplot(line @b @at, lcolor(black) lwidth(medium)) c > iopts(lpattern(dash)recast(rcap) lcolor(gray*0.7) msize(medium)) msymbol(circle_ho > llow) mcolor(black) msize(large) scheme(s1mono) graphregion(fcolor(white) lcolor(w > hite)) plotregion(fcolor(white))legend(off) option fmt() not allowed r(198); . help fmt 这个报错了,你写代码的时候不要有换行符
最新发布
11-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值