简体   繁体   中英

Command find unix ,linux

we write a command that takes a number n through stdin. The command must write the number to the standard output obtained by writing the numbers 1,2,3....,n in succession, alternating the -(subtraction) and +(addition) operators between any two consecutive digits, and calculate the expression thus obtained. For n = 12 we get for example: 1-2+3-4+5-6+7-8+9-1+0-1+1-1+2 = 5

$ echo 12 | ...
5
$ echo 82 | ...
 14

we need to change (...) with a code to get the answer.

Something like this. I'm using busybox awk to accomplish this task.

Example 1:

echo 12 | awk '{ for(i=1;i<=$0;++i) { len=split(i,nums,""); for(j=1;j<=len;++j) arr[++n]=nums[j] }} END { for(i=1;i<=n;++i) if(i%2==0) { r-=arr[i]} else { r+=arr[i] } print r }'

Output:

5

Example 2:

echo 82 | awk '{ for(i=1;i<=$0;++i) { len=split(i,nums,""); for(j=1;j<=len;++j) arr[++n]=nums[j] }} END { for(i=1;i<=n;++i) if(i%2==0) { r-=arr[i]} else { r+=arr[i] } print r }'

Output:

19

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM