This is my code:
let input = document.getElementById('f2f11c3');
input.addEventListener('input', addcommas, false);
function addcommas() {
var v = document.getElementById('f2f11c3');
var t = v.value.replace(/\D/g, '');
var i, temp = '';
for (i = t.length; i >= 0; i -= 2) {
if (i == t.length) {
temp = t.substring(i - 2, i);
} else {
if (t.substring(i - 2, i) != "")
temp = t.substring(i - 2, i) + ':' + temp;
}
if (i < 0) {
temp = t.substring(0, i + 2) + ':' + temp;
break;
}
}
v.value = temp;
}
<input type="text" value="" maxlength="8" id="f2f11c3" />
But entered numbers can be greater than 24. Can you fully adapt to the time format?
Example: 23:59:59 and one more 00:00:00
Short answer
Take the string
Split that
Use modulo operator to get the result
Example
var time="24:70:65"; // Suppose we have this time
var parts=time.split(":");// Split the time with :
var part1=(+parts[0] % 24)
var part2=(+parts[1] % 60)
var part3=(+parts[2] % 60)
// Now to get answer in two digits you can
part1 = ("0" + part1).slice(-2);
part2 = ("0" + part2).slice(-2);
part3 = ("0" + part3).slice(-2);
console.log(`${part1}:${part2}:${part3}`)
Hope this will work
Related
while (a) {
b.push(a % 10);
a = Math.floor(a / 10);
if (b == 7) {
n = n + 1;
}
console.log("<br><br>number of 7's:" + n);
}
This is what I have come up with. The output is one of the numbers has seven; if not, then zero. I want the program to count the number of times seven appears in a number.
You can convert the number to a string, and then count how many times a character = 7:
let n = 7326577
let cnt = 0;
let strN = '' + n;
for(let c of strN)
if(c == '7')
cnt ++
console.log('Number of 7\'s in number: ' + cnt)
Following you approach you need to store the last digit to a different variable and use that for checking if it is a 7
var a = 709728457;
var b = [];
var n = 0;
while (a) {
const lastDigit = a % 10;
b.push(lastDigit); // if you still need to store all digits
a = Math.floor(a / 10);
if (lastDigit == 7) {
n = n + 1;
}
}
console.log("number of 7's:" + n);
var a = 7686774737
var no = String(a).split('').filter(e=>e==7).length;
console.log(no)
can anyone come with an idea of how to sort an integer without using an array, and without using string methods as well as sort() method?
for example
input: 642531
output: 123456
I started by writing 2 simple functions - one which checks the length of the number, the other one splits the integer at some point and switches between 2 desired numbers. Below are the 2 functions.
I got stuck with the rest of the solution...
function switchDigits(num, i) { // for input: num=642531, i = 4 returns 624135
let temp = num;
let rest = 0;
for (let j = 0; j < i - 1; j++) {
rest = rest * 10;
rest = rest + temp % 10;
temp = (temp - temp % 10) / 10;
}
let a = temp % 10;
temp = (temp - a) / 10;
let b = temp % 10;
temp = (temp - b) / 10;
temp = Math.pow(10, i - 2) * temp;
temp = temp + 10 * a + b;
temp = Math.pow(10, i - 1) * temp;
temp = temp + rest;
return temp;
}
function checkHowManyDigits(num) { //input: 642534, output: 6 (length of the integer)
let count = 0;
while (num > 0) {
let a = num % 10;
num = (num - a) / 10;
count++;
}
return count;
}
let num = 642534;
let i = checkHowManyDigits(num);
console.log(switchDigits(num));
It actually complicated requirement and so does this answer. It's pure logic and as it is it's a question from a test you should try understanding the logic on your own as a homework.
function checkHowManyDigits(num) { //input: 642534, output: 6 (length of the integer)
let count = 0;
while (num > 0) {
let a = num % 10;
num = (num - a) / 10;
count++;
}
return count;
}
function sortDigit(numOriginal) {
let i = checkHowManyDigits(numOriginal);
let minCount = 0;
let min = 10;
let num = numOriginal;
while (num > 0) {
let d = num % 10;
num = (num - d) / 10;
if (d < min) {
min = d;
minCount = 0;
} else if (d === min) {
minCount++;
}
}
let result = 0;
while (minCount >= 0) {
result += min * Math.pow(10, i - minCount - 1);
minCount--;
}
let newNum = 0;
num = numOriginal;
while (num > 0) {
let d = num % 10;
num = (num - d) / 10;
if (d !== min) {
newNum = newNum * 10 + d;
}
}
if (newNum == 0) return result;
else return result += sortDigit(newNum);
}
console.log(sortDigit(642531));
You could have a look to greater and smaller pairs, like
64
46
The delta is 18, which gets an idea if you compare other pairs, like
71
17
where the delta is 54. Basically any difference of two digits is a multiple of 9.
This in mind, you get a function for taking a single digit out of a number and a single loop who is sorting the digits by using the calculated delta and subtract the value, adjusted by the place.
function sort(number) {
const
getDigit = e => Math.floor(number / 10 ** e) % 10,
l = Math.ceil(Math.log10(number)) - 1;
let e = l;
while (e--) {
const
left = getDigit(e + 1),
right = getDigit(e);
if (left <= right) continue;
number += (right - left) * 9 * 10 ** e;
e = l;
}
return number;
}
console.log(sort(17)); // 17
console.log(sort(71)); // 17
console.log(sort(642531)); // 123456
console.log(sort(987123654)); // 123456789
So eventually I found the best solution.
*This solution is based on a Java solution I found in StackOverFlow forums.
let store = 0;
function getReducedNumbr(number, digit) {
console.log("Remove " + digit + " from " + number);
let newNumber = 0;
let repeateFlag = false;
while (number>0) {
let t = number % 10;
if (t !== digit) {
newNumber = (newNumber * 10) + t;
} else if (t == digit) {
if (repeateFlag) {
console.log(("Repeated min digit " + t + " found. Store is : " + store));
store = (store * 10) + t;
console.log("Repeated min digit " + t + " added to store. Updated store is : " + store);
} else {
repeateFlag = true;
}
}
number = Math.floor(number / 10);
}
console.log("Reduced number is : " + newNumber);
return newNumber;}
function sortNum(num) {
let number = num;
let original = number;
let digit;
while (number > 0) {
digit = number % 10;
console.log("Last digit is : " + digit + " of number : " + number);
temp = Math.floor(number/10);
while (temp > 0) {
console.log("subchunk is " + temp);
t = temp % 10;
if (t < digit) {
digit = t;
}
temp = Math.floor(temp/10);
}
console.log("Smallest digit in " + number + " is " + digit);
store = (store * 10) + digit;
console.log("store is : " + store);
number = getReducedNumbr(number, digit);
}
console.log(("Ascending order of " + original + " is " + store));
return store;
}
console.log(sortNum(4214173));
you can see how it works here https://jsfiddle.net/9dpm14fL/1/
I'm trying to work a given set of parameters that define the minimum value and maximum value (minNumber, maxNumber). Basically, I want to take my minNumber, if it isn't even, find the nearest even number (if 5, use 6) and incremented it by 2 (6, 8, 10, ... maxNumber) until it is <= maxNumber. For example, if my minNumber = 4 and maxNumber = 21, my output = 4, 6, 8, 10, 12, 14, 16, 18, 20
This is my last attempt:
function evenNumbers(minNumber, maxNumber){
i = 0;
output = "" + minNumber + ", " + minNumber * i
if(minNumber % 2 == 0){
for (i = 2; i <= maxNumber; i+2){
output += ", " + minNumber * i
}
}
return output
}
Using this pre-defined set of parameters:
console.log('evenNumbers(4,13) returns: ' + evenNumbers(4, 13));
console.log('evenNumbers(3,10) returns: ' + evenNumbers(3, 10));
console.log('evenNumbers(8,21) returns: ' + evenNumbers(8, 21));
console.log('\n');
But now I'm getting an "out of memory" error. This is my desired output:
And just for the fun of it... here's a simpler version:
<script>
function evenNumbers2(minNumber, maxNumber){
var output = "";
for (var i = minNumber; i <= maxNumber; i++)
{
if (i % 2 == 0)
{
output += ", " + i;
}
}
return output.substring(2,999);
}
console.log('evenNumbers2(4,13) returns: ' + evenNumbers2(4, 13));
console.log('evenNumbers2(3,10) returns: ' + evenNumbers2(3, 10));
console.log('evenNumbers2(8,21) returns: ' + evenNumbers2(8, 21));
</script>
I think this is what you are looking for:
<script>
function evenNumbers(minNumber, maxNumber){
if(minNumber % 2 != 0){ minNumber++ }
var output = "" + minNumber ;
for (var i = minNumber + 2; i <= maxNumber; i = i + 2)
{
output += ", " + i;
}
return output
}
console.log('evenNumbers(4,13) returns: ' + evenNumbers(4, 13));
console.log('evenNumbers(3,10) returns: ' + evenNumbers(3, 10));
console.log('evenNumbers(8,21) returns: ' + evenNumbers(8, 21));
</script>
The function for getting the array of even numbers in the range
function even(a, b) {
var a = (a + 1) & 0xfffffffe;
var r = [];
for (; a <= b; a += 2) {
r.push(a);
}
return r;
}
This should be it:
function evenNumbers(minNumber, maxNumber){
var output = "";
if(minNumber % 2 != 0){
output = minNumber + 1;
for (i = minNumber+3; i <= maxNumber; i+=2){
output += ", " + i;
}
}
else{
output = minNumber;
for (i = minNumber+2; i <= maxNumber; i+=2){
output += ", " + i;
}
}
return output;
}
You forgot the "=" while updating the i value.
I also tried to clean up a bit the function.
Btw, if(x % 2 == 0) is true it means that x is even, if it is !=0 it is odd.
function evenNumbers(minNumber, maxNumber) {
# Check if even; add 1 to number if not
if (minNumber % 2 != 0) {
minNumber++
}
var arr = []
# Iterate through numbers, incrementing minNumber
# and creating array of output
while (minNumber <= maxNumber) {
arr.push(minNumber);
minNumber += 2;
}
# return array formatted as string with commas
return arr.join(',');
}
I am using javascript to format the number with commas , it was working very fine.
But now the problem is if a value is comming in negative for example : -792004
It is returning the output like : -,792,004 that is comma is in the start.
How can I modify this method ?
Here is my code :
function Comma(number) {
number = '' + number;
if (number.length > 3) {
var mod = number.length % 3;
var output = (mod > 0 ? (number.substring(0, mod)) : '');
for (i = 0; i < Math.floor(number.length / 3); i++) {
if ((mod == 0) && (i == 0))
output += number.substring(mod + 3 * i, mod + 3 * i + 3);
else
output += ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
}
return (output);
} else return number;
}
The simplest way I know which will helps you is toLocaleString() method on number:
var x = 10033001;
var y = -10033001;
console.log(x.toLocaleString(), y.toLocaleString());
But for correction of your code, you can remove number sign with Math.abs and add it after with Math.sign.
var sign = Math.sign(number);
number = Math.abs(number);
// Do the conversion
return (sign < 0) ? ("-" + output) : output;
Try this:
const comma = function(number) {
const prefix = number < 0 ? '-' : ''
number = String(Math.abs(number))
if (number.length > 3) {
const mod = number.length % 3
let output = (mod > 0 ? (number.substring(0,mod)) : '')
for (let i = 0; i < Math.floor(number.length / 3); i++) {
if (mod === 0 && i === 0)
output += number.substring(mod+ 3 * i, mod + 3 * i + 3)
else
output+= ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
}
return prefix + output
} else {
return prefix + number
}
}
If the number is negative, it assigns - to prefix. Then it changes number to its absolute value (Math.abs(number)). In the end it returns value with prefix.
I need to increment a value similar to this:
A001 becomes A002
A999 becomes B001
B001 becomes B002
etc
Z999 becomes A001
I can increment an integer like this:
var x = 5;
x++;
Yields x = 6
I can increment an character like this:
var str = 'A';
str = ((parseInt(str, 36)+1).toString(36)).replace(/0/g,'A').toUpperCase();
if (str =='1A') {
str = 'A';
}
Yields the next character in the alphabet.
This code seems to work, but I'm not sure it's the best way?
var str = 'Z999';
if (str == 'Z999') {
results = 'A001';
}
else {
var alpha = str.substring(0,1);
num = str.substring(1,4);
if (alpha != 'Z' && num == '999') {
alpha= ((parseInt(alpha, 36)+1).toString(36)).replace(/0/g,'A').toUpperCase();
}
num++;
var numstr = num + "";
while (numstr .length < 3) numstr = "0" + numstr ;
if (numstr == 1000) {
numstr = '001';
}
results = alpha + numstr;
}
results seems to give the correct answer. Yes?
You could use parseInt(input.match(/\d+$/), 10) to extract the number at the end of the string and input.match(/^[A-Za-z]/) to retreive the single character at the beginning.
Increment and pad the number accordingly, and increment the character if the number is over 999 by retrieving the character's character code and incrementing that.
String.fromCharCode(letter.charCodeAt(0) + 1);
Full code/example:
function incrementNumberInString(input) {
var number = parseInt(input.trim().match(/\d+$/), 10),
letter = input.trim().match(/^[A-Za-z]/)[0];
if (number >= 999) {
number = 1;
letter = String.fromCharCode(letter.charCodeAt(0) + 1);
letter = letter === '[' ? 'A': (letter === '{' ? 'a' : letter);
} else {
number++;
}
number = '000'.substring(0, '000'.length - number.toString().length) + number;
return letter + number.toString();
}
document.querySelector('pre').textContent =
'A001: ' + incrementNumberInString('A001')
+ '\nA999: ' + incrementNumberInString('A999')
+ '\nB001: ' + incrementNumberInString('B001')
+ '\nB044: ' + incrementNumberInString('B044')
+ '\nZ999: ' + incrementNumberInString('Z999');
<pre></pre>
Output:
A001: A002
A999: B001
B001: B002
B044: B045
D7777: E001
Try storing A-Z in an array , using String.prototype.replace() with RegExp /([A-Z])(\d+)/g to match uppercase characters , digit characters . Not certain what expected result is if "Z999" reached ?
var arr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
var spans = document.querySelectorAll("span");
function count(el) {
var data = el.innerHTML.replace(/([A-Z])(\d+)/g, function(match, text, n) {
var _text, _n;
if (Number(n) === 999) {
_text = arr[ arr.indexOf(text) + 1 ];
} else {
_text = text
};
// `"Z999"` condition ?
if (_text === undefined) {
return "<mark>" + text + n + "</mark>"
}
_n = Number(n) + 1 < 1000 ? Number(n) + 1 : "001";
if (n < 10) {
return _text + n.slice(0, 2) + _n
};
if (n < 100) {
return _text + n.slice(0, 1) + _n
} else {
return _text + _n
}
});
el.innerHTML = data
}
for (var i = 0; i < spans.length; i++) {
count(spans[i])
}
<span>A001</span>
<span>A999</span>
<span>B001</span>
<span>C999</span>
<span>D123</span>
<span>Z999</span>