Division Stringified Coderbyte Solution

0

Have the function DivisionStringified(num1,num2) take both parameters being passed, divide num1 by num2, and return the result as a string with properly formatted commas. If an answer is only 3 digits long,return the number with no commas (ie. 2 / 3 should output "1"). 

For example: if num1 is 123456789 and num2 is 10000 the output should be "12,345".

Division Stringified Java


import java.util.Scanner;

public class DivisionStringified {
String DivisionStringified(int num1, int num2) {

String value = String.valueOf(Math.round((float)num1/num2));

char[] chars = value.toCharArray();
StringBuilder builder = new StringBuilder();
int commaCounter = 3;

for(int i = chars.length - 1; i >= 0; i--)
{
builder.insert(0, chars[i]);
commaCounter--;

if(commaCounter == 0 && i != 0)
{
builder.insert(0, ",");
commaCounter = 3;
}
}

return builder.toString();
}

public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
DivisionStringified c = new DivisionStringified();
System.out.print(c.DivisionStringified(123456789, 10000));
}
}

Division Stringified In Ruby


def DivisionStringified(n1,n2)
n = (n1.to_f/n2.to_f).round
arr = n.to_s.split("").reverse
return "#{n.to_s}" if arr.length <= 3
n_with_commas = []
arr.each_with_index do |digit,i|
n_with_commas << digit
if (i + 1) % 3 == 0
n_with_commas << ","
end
end
n_with_commas.reverse.join("")
end
# keep this function call here
puts DivisionStringified(STDIN.gets)

Division Stringified In JavaScript

Using the JavaScript language, have the function DivisionStringified(num1,num2) take both parameters being passed, divide num1 by num2, and return the result as a string with properly formatted commas. If an answer is only 3 digits long, return the number with no commas (ie. 2 / 3 should output "1"). 

For example: if num1 is 123456789 and num2 is 10000 the output should be "12,345".  


function DivisionStringified(num1,num2) {
var tot = Math.round(num1 / num2);
var newNum = tot.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");

return newNum;
}

Explanation:

The first step is to divide the two number and get a whole number that you can format according to the directions. I use RegExp to format the number

Disclaimer: The above Problem is generated by Coderbyte but the Solution is provided by ShouterFolk.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Accept !