【问题标题】:How to reverse the digits of a uint in solidity?如何在solidity中反转uint的数字?
【发布时间】:2021-09-13 23:32:02
【问题描述】:

我正在尝试编写一个函数来反转 Solidity 智能合约中 uint 的数字。

我看到this answer here 展示了如何通过从后到前循环传递字符串的字节来反转 string,但由于我只关心整数,我想知道是否存在是一种只使用整数的方法,并且能够适当地处理溢出。

谢谢!

【问题讨论】:

    标签: ethereum solidity smartcontracts


    【解决方案1】:

    四处搜索我发现 this answer 可以解决 C 中的这个问题。我能够对其进行调整以在 Solidity 中工作。

    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.0;
    
    contract Reverse {
        function reverse_recurse(uint i, uint r) internal returns(uint) {
          if (i != 0) {
            uint least_digit = i % 10;
            if (r >= type(uint).max / 10 && (r > type(uint).max / 10 || least_digit > type(uint).max % 10)) {
              return 0; /// Overflow
            }
            r = reverse_recurse(i / 10, r * 10 + least_digit);
          }
          return r;
        }
        
        // Reverses digits in a uint, overflow returns 0
        function reverse_int(uint i) public returns(uint) {
          return reverse_recurse(i, 0);
        }
    }
    
     decoded input  { "uint256 i": "12345" }
     decoded output { "0": "uint256: 54321" } 
    

    与 C 解决方案不同,这仅适用于无符号整数,因为这正是我所需要的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-06
      • 2022-04-26
      • 1970-01-01
      • 2020-07-18
      • 2022-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多