Logic Tests Series (2) - DECR 逻辑测试系列之二 - DECR

in #cn7 years ago (edited)

@justyy 's series of Logits Tests:

What you can do with this tiny programming language with only 4 instructions? Today, we are going to implement the DECR function which decrements the variable by one, for example, DECR(X) where X=5 will make X=4.

DECR(X) {

}

The only 4 instructions are: INCR, LOOP, ZERO and ASGN. And all variables hold non-negative integers. To make X decremented by 1, we can increment a temp variable by (X-1) times..

DECR(X) {
   ZERO(V1)
   LOOP(X) {
     ASGN(X, V1)
     INCR(V1)
  }
}

We translate this to C++, which might be a bit easy to understand.

void decr(unsigned int &x) {
   int v1 = 0;
   int xx = x;
   for (; x > 0; -- x) {
      xx = v1;
      v1 ++;
   }
   x = xx;
}

If you change the value of the loop variable x, the loop iteration count may be altered. Therefore, we declare a temp variable xx and assign the xx to X after loop when it gets incremented (x-1) times.


Image Credit: pixabay.com

@justyy 的逻辑测试系列:

这种只有4条语句的语言能做什么呢?今天我们来定义一个DECR函数,该函数就是把 变量 X 减一。

DECR(X) {

}

要求填写函数体,使用 INCR、LOOP、ZERO、和 ASGN 仅有的4个语句。我们不妨想一下,已知变量 X 是非负整数,那么我们只需要 循环 X-1次,每次把X从0加1即可。

DECR(X) {
   ZERO(V1)
   LOOP(X) {
     ASGN(X, V1)
     INCR(V1)
  }
}

我们翻译成 C++, 可能比较好懂一些:

void decr(unsigned int &x) {
   int v1 = 0;
   int xx = x;
   for (; x > 0; -- x) {
      xx = v1;
      v1 ++;
   }
   x = xx;
}

由于C++的 for 里改变 x 值会改变循环次数,所以我们用了一个临时变量 xx。

STEEMIT 中文区 RSS 工具和名单:

Chrome 插件:

Steem API:

最近帖子:

STEEMIT CN RSS Tools:

Chrome Extensions:

Steem API:

Recent Posts:

// Later, it may be reposted to my blogs: justyy.com, helloacm.com and codingforspeed.com 稍后同步到我的中文博客和英文计算机博客

Originally published at https://steemit.com Thank you for reading my post, feel free to Follow, Upvote, Reply, ReSteem (repost) @justyy which motivates me to create more quality posts.

原文首发于 https://Steemit.com 首发。感谢阅读,如有可能,欢迎Follow, Upvote, Reply, ReSteem (repost) @justyy 激励我创作更多更好的内容。

Sort:  

Thanks for the information. I'm eager to learn from this programming.

This post recieved an upvote from minnowpond. If you would like to recieve upvotes from minnowpond on all your posts, simply FOLLOW @minnowpond

This post recieved an upvote from minnowpond. If you would like to recieve upvotes from minnowpond on all your posts, simply FOLLOW @minnowpond