如何将Java整数的前三个字符替换为111?

huangapple go评论99阅读模式
英文:

How do I replace the first three characters of a Java integer by 111?

问题

我在Java中有一个整数。如何将其前三位替换为111(或任何其他数字),例如将783729变为111729?非常感谢!

英文:

I have an integer in java. How do I replace its’ first three numbers with 111(or any other number), for example turning 783729 into 111729?
Many thanks!

答案1

得分: 1

你可以将它转换为字符串,然后替换前三个字母。

String s = String.valueOf(783729);
int i = Integer.parseInt(s.replace(s.substring(0, 3), "111"));
英文:

You could convert it into a string and then replace the first three letters.

String s = String.valueOf(783729);
int i = Integer.parseInt(s.replace(s.substring(0, 3), "111"));

答案2

得分: 0

将整数转换为字符串,替换前三个字符,然后再将其转换回整数。如果在编码过程中感到困难,请尝试自行解决。如果您在编码过程中遇到问题,请将您的代码和所遇到的问题发布出来。

英文:

Convert the integer to string replace the first three characters and convert it back to integer.kindly try to do it yourself. if you feel stuck during coding post your code along with the problem you face.

答案3

得分: 0

你可以通过简单的算术运算而无需转换为字符串来实现这一点:

// 假设num初始值至少为999。
int replaceWith111(int num) {
  if (num < 1000) {
    return 111;
  }
  return 10 * replaceWith111(num / 10) + (num % 10);
}
英文:

You can do this without converting to a string using simple arithmetic:

// Assumes that num is initially at least 999.
int replaceWith111(int num) {
  if (num &lt; 1000) {
    return 111;
  }
  return 10 * replaceWith111(num / 10) + (num % 10) 
}

答案4

得分: 0

当然,如果你只是需要完成这个任务,你可以将其转换为String,然后在那里进行替换。

然而,只是为了好玩,下面是如何仅使用Math函数和运算符来完成这个任务。不处理负数——这留给读者作为练习 如何将Java整数的前三个字符替换为111?

int s = 111;
int n = 783729;

int ds = (int)Math.ceil(Math.log10(s));
int dn = (int)Math.ceil(Math.log10(n));
int b = (int)Math.pow(10, dn-ds);
int sn = s * b + n % b;

System.out.println(sn);

输出:

111729
英文:

Obviously if you just need to get this done you'd convert to String and do the substitution there.

However, just for fun, here's how you could do it using only Math functions and operators. Doesn't handle negative numbers - that's left as an exercise fo the reader 如何将Java整数的前三个字符替换为111?

int s = 111;
int n = 783729;

int ds = (int)Math.ceil(Math.log10(s));
int dn = (int)Math.ceil(Math.log10(n));
int b = (int)Math.pow(10, dn-ds);
int sn = s * b + n % b;

System.out.println(sn);

Output:

111729

huangapple
  • 本文由 发表于 2020年4月4日 22:06:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/61029321.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定