1556. 千位分隔数
C代码:
char * thousandSeparator(int n){
char* str = (char*)malloc(sizeof(char) * 20);
int len = sprintf(str, "%d", n);
int len2 = 0;
if (len % 3 == 0) {
len2 = len+ len / 3 - 1;
} else {
len2 = len + len / 3;
}
char* ans = (char*)malloc(sizeof(char) * (len2 + 1));
ans[len2] = '\0';
for(int i = len - 1; i >= 0; --i) {
if (len - 1 - i != 0 && (len - 1 - i) % 3 == 0) {
ans[--len2] = '.';
}
ans[--len2] = str[i];
}
return ans;
}
Java代码:
class Solution {
public String thousandSeparator(int n) {
int count = 0;
StringBuffer ans = new StringBuffer();
do {
int cur = n % 10;
n /= 10;
ans.append(cur);
++count;
if (count % 3 == 0 && n != 0) {
ans.append('.');
}
} while (n != 0);
ans.reverse();
return ans.toString();
}
}