C(gcc),104个字节
f(b,o,u,n,c,y){for(o=u=0;b;u+=y?0:o+0*--b,++o)for(n=o,y=3;n/10;)c=n%10,n/=10,y&=(c-=n%10)<0?:c?2:y;b=u;}
在这里在线尝试。
取消高尔夫:
f(n, // function: return type and type of arguments defaults to int;
// abusing extra arguments to declare variables
i, // number currently being checked for bounciness
s, // sum of the bouncy numbers
j, // copy of i to be used for checking bounciness in a loop
p, // used for investigating the last digit of j
b) { // whether i is not bouncy; uses the two least significant bits to indicate increasing/decreasing
for(i = s = 0; // check numbers from zero up; initial sum is zero
n; // continue until we have n bouncy numbers
s += b ? 0 // not bouncy, no change to the sum
: i + 0* --n, // bouncy, add it to the sum and one less bouncy number to go
++i) // either way, move to the next number
for(j = i, b = 3; j/10; ) // make a copy of the current number, and truncate it from the right until there is just one digit left
// bounciness starts as 0b11, meaning both increasing and decreasing; a value of 0 means bouncy
p = j % 10, // get the last digit
j /= 10, // truncate one digit from the right
b &= // adjust bounciness:
(p -= j % 10) // compare current digit to the next
< 0 ? // not an increasing number, clear second to least significant bit
: p ? 2 // not a decreasing number, clear least significant bit
: b; // keep it the same
n = s; // gcc shortcut for return s
}
sort
检查号码是否与原始号码相同吗?那是使用内置(sort
),但严格来说并不是检查它是否在增加的内置。请查看“ 不可观察的程序要求”,并在“应避免的事情”元文章中执行X不带Y的操作。