在Java中向给定数字添加一个字符作为千位分隔符
给定一个整数n和字符ch ,返回一个字符串,使用该字符作为给定数字的千位分隔符。
例子:
Input: n=1234 , ch =’.’
Output: 1.234
In the above-given input, “.” character is used as the thousands separator and is placed between hundreds and thousands of places starting from the right. The obtained output is returned as String Format.
Input: n=123456789 , ch =’.’
Output: 123.456.789
方法:
- 将数字转换为字符串。
- 从右侧开始字符串遍历。
- 每三位数字后添加分隔字符
下面是使用相同方法使用Java的代码。
Java
// Java Program for Adding a character as thousands separator
// to the given number and returning in string format
class GFG {
static String thousandSeparator(int n, String ch)
{
// Counting number of digits
int l = (int)Math.floor(Math.log10(n)) + 1;
StringBuffer str = new StringBuffer("");
int count = 0;
int r = 0;
// Checking if number of digits is greater than 3
if (l > 3) {
for (int i = l - 1; i >= 0; i--) {
r = n % 10;
n = n / 10;
count++;
if (((count % 3) == 0) && (i != 0)) {
// Parsing String value of Integer
str.append(String.valueOf(r));
// Appending the separator
str.append(ch);
}
else
str.append(String.valueOf(r));
}
str.reverse();
}
// If digits less than equal to 3, directly print n
else
str.append(String.valueOf(n));
return str.toString();
}
// Driver code
public static void main(String[] args)
{
int n = 123456789;
String ch = ".";
System.out.println(thousandSeparator(n, ch));
}
}
输出
123.456.789
时间复杂度: O(n)