【问题标题】:How do you add digits to the front of a number?如何在数字前面添加数字?
【发布时间】:2023-02-04 03:03:12
【问题描述】:

如何在不使用字符串的情况下将数字添加到数字的开头(左侧)?

我知道如果你试试这个:

(一些伪代码)

假设我尝试制作数字 534

int current = 5;
int num = 0;

num = (num*10) +current; 

然后

int current = 3;
int num = 5

num = (num*10) + current;

将使:53

然后

int current = 4;
int num = 53;

num = (num*10) + current;

将使534

它会不断在数字的右侧添加数字。

但是,我对您如何做相反的事情感到有些困惑。你如何在左边添加数字,而不是 534 而是 435?

【问题讨论】:

  • 欢迎来到堆栈溢出。请使用 tour 了解 Stack Overflow 的工作原理,并阅读 How to Ask 了解如何提高问题的质量。然后检查help center,看看哪些问题是本网站的主题。请显示您尝试过的尝试以及您从尝试中得到的问题/错误消息。

标签: java


【解决方案1】:

在与当前数字相加之前,通过增加 10 的幂来乘以要添加的数字。

int num = 0, pow = 1;
num += 5 * pow;
pow *= 10;
num += 3 * pow;
pow *= 10;
num += 4 * pow; // num = 435 at this point
pow *= 10;
// ...

【讨论】:

    【解决方案2】:

    你可以在 python 中使用一些数学

    import math
    def addLeft(digit, num):
        return digit * 10 ** int(math.log10(num) + 1) + num
    

    请注意,由于精度问题,这对于非常大的数字可能会失败

    >>> addLeft(2, 100)
    2100
    >>> addLeft(3, 99)
    399
    >>> addLeft(6, 99999999999999)
    699999999999999
    >>> addLeft(5, 999999999999999)
    50999999999999999  (oops)
    

    【讨论】:

      【解决方案3】:
      int num = 123;
      int digits = 456;
      
      int powerOfTen = (int) Math.pow(10, (int) (Math.log10(digits) + 1));
      
      int finalNum = digits * powerOfTen + num;
      
      System.out.println(finalNum);  // Output: 456123
      

      digits 中的位数是使用 Math.log10 和 Math.pow 计算的,然后用于确定 digits 乘以的适当的 10 次幂。然后将结果添加到 num 以获得添加数字的最终数字。

      【讨论】:

        猜你喜欢
        • 2023-03-03
        • 1970-01-01
        • 2015-12-03
        • 1970-01-01
        • 1970-01-01
        • 2022-11-14
        • 1970-01-01
        • 1970-01-01
        • 2021-07-13
        相关资源
        最近更新 更多