有多少有效数字?


10

给定一个数字作为输入,请确定它具有多少个有效数字。该数字应作为字符串,因为您必须进行一些特殊的格式化。您很快就会明白我的意思(我认为)。

如果满足以下至少一项要求,则数字为签名。

  • 非零数字始终有效。
  • 两个有效数字之间的任何零都是有效的。
  • 小数部分中的最终零或尾随零仅是有效的。
  • 如果没有小数位,则所有数字都是有效的。
  • 当只有零时,除最后一个零外的所有零都被视为前导零

输入值

数字的字符串或字符串数​​组。它的末尾可能有一个小数点,后面没有数字。它可能根本没有小数点。

输出量

有多少个签名。

例子

1.240 -> 4
0. -> 1
83900 -> 3
83900.0 -> 6
0.025 -> 2
0.0250 -> 3
2.5 -> 2
970. -> 3
0.00 -> 1

相关,但a)没有答案,b)关于计算表达式的答案
Daniel Daniel


您可能想在某个地方明确提及,如果只有零,那么除最后一个零外的所有数字都被视为前导数字(与之相反,除了第一个零之外的所有数字均被视为尾随数字)。
Martin Ender

为什么0.00-> 1?小数点后的两个零不是有效的(根据“最终零或仅十进制部分中的尾随零是有效的”)。
Penguino

@Penguino,正如马丁·恩德(Martin Ender)正确说的那样,如果只有0,则除最后一位以外的所有数字都被视为前导零
Daniel Daniel

Answers:




1

批次,204202字节

@set/ps=
:t
@if %s:.=%%s:~-1%==%s%0 set s=%s:~,-1%&goto t
@set s=%s:.=%
:l
@if not %s%==0 if %s:~,1%==0 set s=%s:~1%&goto l
@set n=0
:n
@if not "%s%"=="" set/an+=1&set s=%s:~1%&goto n
@echo %n%

在STDIN上输入。如果数字不包含.,则删除尾随零,然后删除.和开头的零,除非只有零,否则它将保留一个零。最后,它占用剩余字符串的长度。


我一生中从未见过如此多%的东西:O
user41805

1
@KritixiLithos我以前在一行中管理过16个:codegolf.stackexchange.com/a/86608/17602
Neil

0

Scala,90个字节

& =>(if(&contains 46)&filter(46!=)else&.reverse dropWhile(48==)reverse)dropWhile(48==)size

说明:

& =>               //define an anonymous function with a parameter called &
  (
  if(&contains 46) //if & contains a '.'
    &filter(46!=)    //remove all periods
  else             //else
    &.reverse        //reverse the string
    dropWhile(48==)  //remove leading zeros
    reverse          //and reverse again
  )
  dropWhile(48==) //remove leading zeros
  size            //return the length

0

C#6,163个字节

using System.Linq;
int a(string s)=>System.Math.Max(s.Contains('.')?(s[0]<'1'?s.SkipWhile(x=>x<'1').Count():s.Length-1):s.Reverse().SkipWhile(x=>x<'1').Count(),1);

不打高尔夫球

int a(string s)=>                                  
    System.Math.Max(
        s.Contains('.')                                // Has decimal place?
            ?(                                         // Has decimal place!
                s[0]<'1'                               // Start with '0' or '.'?
                    ?s.SkipWhile(x=>x<'1').Count()     // Yes: Skip leading '0' and '.', then count rest... But gives 0 for "0." and "0.00"
                    :s.Length-1)                       // No: Count length without decimal place
            :s.Reverse().SkipWhile(x=>x<'1').Count()   // No decimal place: Skip trailing '0' and count rest
    ,1);                                               // For "0." and "0.00"
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.