Decimal Representation of a number (comma separated) in java
package challenges;
import java.util.Stack;
public class DecimalRepresentation {
public static void main(String[] args) {
System.out.println(decimalRepresent(123456789));
}
private static String decimalRepresent(int no) {
String noStr = Integer.toString(no);
char[] charArr = noStr.toCharArray();
StringBuffer sbr = new StringBuffer();
Stack<Character> stack = new Stack<Character>();
int pos = 0;
for (int i=charArr.length-1; i>=0; i--) {
if (pos == 3) {
stack.push(',');
pos = 0;
} else {
pos++;
stack.push(charArr[i]);
}
}
while(!stack.isEmpty()) {
sbr.append(stack.pop());
}
return sbr.toString();
}
}
import java.util.Stack;
public class DecimalRepresentation {
public static void main(String[] args) {
System.out.println(decimalRepresent(123456789));
}
private static String decimalRepresent(int no) {
String noStr = Integer.toString(no);
char[] charArr = noStr.toCharArray();
StringBuffer sbr = new StringBuffer();
Stack<Character> stack = new Stack<Character>();
int pos = 0;
for (int i=charArr.length-1; i>=0; i--) {
if (pos == 3) {
stack.push(',');
pos = 0;
} else {
pos++;
stack.push(charArr[i]);
}
}
while(!stack.isEmpty()) {
sbr.append(stack.pop());
}
return sbr.toString();
}
}
Comments
Post a Comment