首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >一种常用的长整数算法

一种常用的长整数算法
EN

Stack Overflow用户
提问于 2020-12-02 11:01:34
回答 1查看 50关注 0票数 0

我的想法表明,我有两个类的通用代码,我应该使之成为一个由于干规则(不要重复自己)。

代码语言:javascript
复制
class LongPersistence {
    public void storeSomeNiceNumber(@NotNull Long l) {
            if (l < 0) {
                throw new RuntimeException("value should not be negative");
            }
            someNicePersistence.store(new String(l).getBytes());
        }
    }

    public Long retrieveSomeNiceNumber() {
        try {
            byte[] bytesRepr someNicePersistence.retrieve();
            Long value = Long.parseLong(new String(bytesRepr));
            return value;
        } catch (SomeNicePersistenceException e) {
            return 0L;
        }
    }
}

所以我开始工作..。

代码语言:javascript
复制
class Persistence<N extends Number> {

..。失败的原因是:

  1. 数字不能与0相比。
  2. i不能将0返回到数字。

我认为在定义良好的语言中,这应该是可能的,正如我到目前为止一直在考虑的那样。我是不是遗漏了什么?请建议如何使此算法对Long和Integer通用(并作为任意数字的A+任务)。

EN

回答 1

Stack Overflow用户

发布于 2020-12-02 18:37:06

由于@VGR,我了解到我需要java.lang.Number类的数学逻辑,它的目的是将数字仅存储为对象(类似于变体类型),因此我已经将数学具体化到另一个接口,在我看来,这更有意义。

代码语言:javascript
复制
public interface NumberMath<E extends Number> {
    E parse(String string);
    String toString(E e);
    E zero();
    int signum(E e);
}

class NumberPersistence<E extends Number> {

    private final NumberMath<E> math;
    private final SomeNicePersistence someNicePersistence;

    public NumberPersistence(NumberMath<E> math, SomeNicePersistence persistence) {
        this.someNicePersistence = persistence;
        this.math = math;
    }

    public void storeSomeNiceNumber(E l) {

        if (math.signum(l) < 0) {
            throw new RuntimeException("value should not be negative");
        }
        someNicePersistence.store(math.toString(l).getBytes());

    }

    public E retrieveSomeNiceNumber() {

        try {
            byte[] bytesRepr = someNicePersistence.retrieve();
            E value = math.parse(new String(bytesRepr));
            return value;
        } catch (SomeNicePersistenceException e) {
            return math.zero();
        }
    }
}

我把E限制为数字,但老实说,在这种情况下,它不再是必需的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65106773

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档