Home > Enterprise >  Command find unix ,linux
Command find unix ,linux

Time:10-18

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.

CodePudding user response:

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
  • Related