Skip to content

Instantly share code, notes, and snippets.

@Rafe
Created April 2, 2013 14:28
Show Gist options
  • Save Rafe/5292630 to your computer and use it in GitHub Desktop.
Save Rafe/5292630 to your computer and use it in GitHub Desktop.
Solving number to words problem from http://code-warrior.herokuapp.com.

#Transfer word to numbers

Given an integer between 0 and 999,999, print an English phrase that describes the integer (eg, "One Thousand, Two Hundred and Thirty Four;

####power by code-warrior

var singles = [
'', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten',
'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
];
var tenth = ['', 'ten', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
var unit = ['', 'thousand', 'million', 'billion'];
module.exports = function (n) {
var result = [];
var len = n.toString().length;
while (len > 0) {
//get the , position
var digit = Math.ceil(len / 3) - 1;
var num = Math.floor(n / Math.pow(1000, digit));
var hundred = Math.floor(num / 100);
if( hundred >= 1) {
result.push(singles[hundred]);
result.push('hundred');
}
var ten = Math.floor(num % 100);
if( ten <= 20) {
result.push(singles[ten]);
} else {
var a = Math.floor(ten / 10);
result.push(tenth[a]);
var b = ten % 10;
result.push(singles[b]);
}
n = n % Math.pow(1000, digit);
result.push(unit[digit]);
len = len - 3;
}
return result.join(' ').trim();
}
{
"id": "8",
"name": "number to words",
"level": "basic",
"author": "CareerCup"
}
var func = require("./");
var expect = require("expect.js")
describe("func", function () {
it("can return single words of number", function() {
expect(func(1)).to.eql("one");
expect(func(2)).to.eql("two");
expect(func(3)).to.eql("three");
expect(func(4)).to.eql("four");
expect(func(5)).to.eql("five");
expect(func(6)).to.eql("six");
expect(func(7)).to.eql("seven");
expect(func(8)).to.eql("eight");
expect(func(9)).to.eql("nine");
});
it("can return double digits words", function() {
expect(func(10)).to.eql("ten");
expect(func(21)).to.eql('twenty one');
expect(func(12)).to.eql('twelve');
expect(func(13)).to.eql('thirteen');
expect(func(17)).to.eql('seventeen');
});
it("can return 3 digits words", function() {
expect(func(123)).to.eql('one hundred twenty three');
expect(func(430)).to.eql('four hundred thirty');
expect(func(401)).to.eql('four hundred one');
});
it("can return 5 digits words", function() {
expect(func(12345)).to.eql('twelve thousand three hundred fourty five');
});
it("can return 6 digits words", function() {
expect(func(123456)).to
.eql('one hundred twenty three thousand'
+ ' four hundred fifty six');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment