Get each digit of a number - javascript

What's the best way to get the Nth digit of a number in javascript?
For example, for 31415926, the function will return 1 if N=2.
EDIT: And if possible, tu return directly a number, not a string.
EDIT 2: It is from left to right.

Try with that : (''+number)[nth] or (''+number)[nth-1] if one-based.

Personally, I would use:
function getNthDigit(number, n){
return parseInt((""+number).charAt(n));
}
But if you don't want it to be in String form ever you could use:
function getNthDigit(number, n){
var num = number,
digits = 0;
do{
num /= 10;
digits++;
}while(num>=1);
num = number / Math.pow(10, (digits - n));
num -= num % 1;
return (num % 10);
}
On second thought, just use the first option.

UPDATE: I didn't consider the fact that it was counting from the right. My bad!
Anyway, considering that the input is STILL a string, I'd use the same function, just with a little tweak.
Why don't you use the CharAt function? I think is the best option, considering the risk of multi-byte strings!!!
EDIT: I forgot the example:
var str = "1234567";
var n = str.charAt(str.length-2); // n is "6"

Related

Need someone who can explain me this code (Decimal to binary converter)

<script>
function calculate() {
var num = document.getElementById("decimal").value; //fetching binary value from html input box.
var bin = [];
while (num > 0) {
bin[bin.length] = num % 2;
num >>= 1; // basically /= 2 without remainder if any
}
document.getElementById("result").innerHTML = "Binary Value: " + bin.reverse().join('');
}
</script>
I am trying to understand this code i can't understand these two lines in this code:
bin[bin.length] = num % 2;
num >>= 1;`
bin[bin.length] = num % 2;
Append a 0 or 1 to bin depending on whether num is even or odd.
num >>= 1;
As the comment says, this divides num by 2 without remainder. Overall, the loop puts the digits of the binary representation of num into bin from least significant to most. That is why it is reversed at the end.
bin[bin.length] is just the index of the number (string,actually) that will be crated. For each bin.reverse() it increments by one. The num is a number in digital form. num >>= 1 just shifts right 1 digits. This has an affect to divine the decimal by 2. bin[bin.length] = num % 2 just result to 0 or 1 and add each time to the string to form the final answer.
I am not sure which part you do not understand. Some operator or the whole logic?
You want to know how bin[bin.length] = ... puts the value in the correct spot. Well, bin starts as an empty array (bin = []) which has length 0. So bin[bin.length] = bin[0] to start and the first thing is inserted appropriately at index 0.
This length property is maintained internally as things are inserted into the array. So it will always insert in the first available slot.
Example: after something has been added at index 0, the length property is updated to 1 and the next insertion is done at bin[bin.length] which is equivalent to bin[1].

Reduce a multi-digit to one-digit -guidance not answer please

goal: take a number like 54321, add the numbers together (5+4+3+2+1 = 15), then take that number (15) add the digits (1+5 = 6), so return 6;
here is my code:
function digital_root(n) {
if (n >=10) {
var digits = n.toString().split('').map(function(item, index) {return parseInt(item)}).reduce(function(a,b){ return a+b});
console.log(digits);
}
}
digital_root(1632)
Can't figure out: How to get that function to repeat over and over until digits is just one number (i.e. less than 10). I have tried a variety of nested functions, but can't seem to get it right.
If possible please point me in the direction to the solution ("try a nesting in a while... or read up on..."), but don't give me the complete code solution ("Use this code chunk:...."). I've developed a bad habit of just reading and copying...
Thank you!
Try this: reference HERE
function digital_root(n) {
var singlesum = 0;
while (n >= 10 ) {
singlesum=0;
while (n > 0) {
var rem;
rem = n % 10;
singlesum = singlesum + rem;
n = parseInt(n / 10);
}
n = singlesum;
}
console.log(singlesum);
}
digital_root(1632)
You can use recursion to solve this.
Write a function makeSingleDigit, which argument will be your number.
You need a base condition with the base step, which in your case stops the recursion when received number is one-digit and returns the number.
If condition is not true, you just need to get another digit from the number by n%10 and sum it with the makeSingleDigit(Math.floor(n/10)). By this, you repeatedly sum digits of new numbers, until function receives one-digit number.
Mathematical solution just for your information: the number, which you want to find is n % 9 === 0 ? 9 : n % 9, thus it is the remainder of the division by 9 if it is not 0, otherwise it is 9.
Here is a very optimal solution to the problem:
function digital_root(n) {
return (n - 1) % 9 + 1;
}
const result = digital_root(1632);
console.log(result);
Well, not a very good solution but you can give a hit.
function digital_root(n) {
if (n >=10) {
var digits = n.toString().split('').map(function(item, index) {return parseInt(item)}).reduce(function(a,b){ return a+b});
console.log(digits);
return(digits);
}
}
var num = 1632;
do{
num = digital_root(num);
}while(num>10);

Codefights: Correct solution but system does not accept it

Experienced codefighters, i have just started using Codefight website to learn Javascript. I have solved their task but system does not accept it. The task is to sum all integers (inidividual digit) in a number. For example sumDigit(111) = 3. What is wrong with my code? Please help me.
Code
function digitSum(n) {
var emptyArray = [];
var total = 0;
var number = n.toString();
var res = number.split("");
for (var i=0; i<res.length; i++) {
var numberInd = Number(res[i]);
emptyArray.push(numberInd);
}
var finalSum = emptyArray.reduce(add,total);
function add(a,b) {
return a + b;
}
console.log(finalSum);
//console.log(emptyArray);
//console.log(res);
}
Here's a faster trick for summing the individual digits of a number using only arithmetic:
var digitSum = function(n) {
var sum = 0;
while (n > 0) {
sum += n % 10;
n = Math.floor(n / 10);
}
return sum;
};
n % 10 is the remainder when you divide n by 10. Effectively, this retrieves the ones-digit of a number. Math.floor(n / 10) is the integer division of n by 10. You can think of it as chopping off the ones-digit of a number. That means that this code adds the ones digit to sum, chops off the ones digit (moving the tens digit down to where the ones-digit was) and repeats this process until the number is equal to zero (i.e. there are no digits left).
The reason why this is more efficient than your method is that it doesn't require converting the integer to a string, which is a potentially costly operation. Since CodeFights is mainly a test of algorithmic ability, they are most likely looking for the more algorithmic answer, which is the one I explained above.

How do i return a number excluding the last digit?

So I have a number like 5467. I want my code to return 546.
I tried taking the last number and subtracting it from the original number but I get 5460 instead of 546.
Combine / with %:
(5467 - (5467 % 10)) / 10
564
Sounds like you also need to divide my 10. You could do something like this:
var number = 5467;
number = number - (number % 10); // This will subtract off the last digit.
number = number / 10;
console.log(number); // 546
We first use the modulo operator % to get the last digit, and we subtract it from number. That reduces the number from 5467 to 5460. Now to chop off the last digit (which is guaranteed to be a 0) we divide by 10 and get 546.
Written more concisely you could do:
number = (number - ( number % 10)) / 10;
There's a few things you can do the most concise being:
Math.floor(num / 10);
Or, convert to a string, remove the last character and convert back to number.
parseInt(num.toString().slice(0, -1));
If string representation would be fine for you then one other way is
var num = 5467,
cut = (num/10).toFixed(); // <-'547'
Well... warning..! i have to say toFixed() method rounds if necessary. So in this particular example it doesn't work.
I dont mind some of the other answers, but i feel that this maybe too fixed on it being a number.
Which it is, but you want to remove the last digit/char, regardless of the number, so why not substr?
http://www.w3schools.com/jsref/jsref_substr.asp
var s = 5467;
s = s.toString().substr(0, s.toString().length - 1);
console.log(s)
or even easier:
var s = (5467).toString();
s = s.substr(0, s.length - 1);
console.log(s)
These dont take into account single digit numbers, so passing in 1 would return blank. To answer that you could simply do a check like:
var s = (1).toString();
if(s.length > 1)
s = s.substr(0, s.length - 1);
console.log(s)
Also, similar question to:
Remove last digits from an int
Remove the last digits of a number (not string)
Removing the last digits in string
To truncate digits from the right hand side until the number is less than 30, keep dividing by 10 and rounding down until a suitable value is reached:
var n = 12341235;
while (n > 30) n = n/10|0;
document.write(n);
The greater than and division operations will coerce n to a number, so it can be a number or string. If ToNumber(n) results in NaN (e.g. n = 'foo'), then the value of n is not modified.
You can simply divide the number by 10 and parseInt()
var num = 5467;
num = parseInt(num/10);
Update :
To repeat the process until the answer is less than 30, use while loop as
var num = 5467;
while(num >= 30) {
num = parseInt(num/10);
}
document.write(num);

How do I zero-fill a number?

I have a working decimal to binary converter, but I want it to ALWAYS show 8 digits,
so if I put in 3 it will say '00000011' and not '11'
Anyone a clue how this can be done?
my code:
<script type="text/javascript">
function ConvertToBinary(dec) {
var bits = [];
var dividend = dec;
var remainder = 0;
while (dividend >= 2) {
remainder = dividend % 2;
bits.push(remainder);
dividend = (dividend - remainder) / 2;
}
bits.push(dividend);
bits.reverse();
return bits.join("");
}
<input type="text" id="txtDec" maxlength="3"/>
<input type="button" value="Convert" onclick="document.getElementById('spBin').innerHTML=ConvertToBinary(document.getElementById('txtDec').value);" />
<span id="spBin"></span>
JavaScript already makes the conversion for you, from a number, using toString method, because you can specify the radix (see the link above):
var n = 13;
console.log(n.toString(2)) // "1101"
If you want add lead zero, in case less then 8, you could have:
var bits = n.toString(2);
console.log("00000000".substr(bits.length) + bits);
With just one method call.
Edit: this answer was written in 2013, nowadays the method padStart can be used instead for the padding:
console.log(n.toString(2).padStart(8, "0"));
How about this:
return String('000000000' + bits.join("")).slice(-8);
Demo (change "dividend" to try with different numbers)
Basically adds 8 zeros to the left and then removes anything more than 8 characters long from the left.
How about before bits.reverse(); You do a while loop like this:
while(bits.length < 8){
bits.push(0);
}
Here's an example solution that will left-pad a number with zeros
#param "num" the number to be left-padded with zeros
#param "width" the number of characters required as a result
#return String the left-padded number
function zeroFill(num, width) {
str = String((new Array(width+1)).join('0') + num).slice(-width)
return str
}
There are other solutions which use a loop to create the zeros.

Categories