How to Reverse a string with numbers, but don't reverse 1 and 0?
I am learning random algorithms, and I am currently stock in one, where I have to reverse a string that contains numbers, but I am not to reverse 1 and 0 in the string e.g, 2345678910 would be 1098765432.
Here's what I've done so far:
function split(str) {
let temp = ;
temp = str.split('');
const backwards = ;
const totalItems = str.length - 1;
for (let i = totalItems; i >= 0; i--) {
backwards.push(temp[i]);
}
return backwards.join('').toString();
}
console.log(split("10 2 3 U S A"));
console.log(split("2345678910"));I am currently having the issue of not reversing the 10.
What am I doing wrong?
javascript algorithm
|
show 7 more comments
I am learning random algorithms, and I am currently stock in one, where I have to reverse a string that contains numbers, but I am not to reverse 1 and 0 in the string e.g, 2345678910 would be 1098765432.
Here's what I've done so far:
function split(str) {
let temp = ;
temp = str.split('');
const backwards = ;
const totalItems = str.length - 1;
for (let i = totalItems; i >= 0; i--) {
backwards.push(temp[i]);
}
return backwards.join('').toString();
}
console.log(split("10 2 3 U S A"));
console.log(split("2345678910"));I am currently having the issue of not reversing the 10.
What am I doing wrong?
javascript algorithm
1
please format you code!
– MrSmith42
10 hours ago
1
OP wantsA S U 3 2 10if I understood correctly
– Pac0
10 hours ago
1
I added the other example mentioned above the snippet into it, as already two answers (mine deleted included) missed that one.
– Pac0
10 hours ago
1
Are we assuming that10is always together and in that order? If so, @OmG answer should be okay.
– Caleb Lucas
10 hours ago
1
What about the string USA101001 ? Should it give 101001ASU ?
– Pac0
10 hours ago
|
show 7 more comments
I am learning random algorithms, and I am currently stock in one, where I have to reverse a string that contains numbers, but I am not to reverse 1 and 0 in the string e.g, 2345678910 would be 1098765432.
Here's what I've done so far:
function split(str) {
let temp = ;
temp = str.split('');
const backwards = ;
const totalItems = str.length - 1;
for (let i = totalItems; i >= 0; i--) {
backwards.push(temp[i]);
}
return backwards.join('').toString();
}
console.log(split("10 2 3 U S A"));
console.log(split("2345678910"));I am currently having the issue of not reversing the 10.
What am I doing wrong?
javascript algorithm
I am learning random algorithms, and I am currently stock in one, where I have to reverse a string that contains numbers, but I am not to reverse 1 and 0 in the string e.g, 2345678910 would be 1098765432.
Here's what I've done so far:
function split(str) {
let temp = ;
temp = str.split('');
const backwards = ;
const totalItems = str.length - 1;
for (let i = totalItems; i >= 0; i--) {
backwards.push(temp[i]);
}
return backwards.join('').toString();
}
console.log(split("10 2 3 U S A"));
console.log(split("2345678910"));I am currently having the issue of not reversing the 10.
What am I doing wrong?
function split(str) {
let temp = ;
temp = str.split('');
const backwards = ;
const totalItems = str.length - 1;
for (let i = totalItems; i >= 0; i--) {
backwards.push(temp[i]);
}
return backwards.join('').toString();
}
console.log(split("10 2 3 U S A"));
console.log(split("2345678910"));function split(str) {
let temp = ;
temp = str.split('');
const backwards = ;
const totalItems = str.length - 1;
for (let i = totalItems; i >= 0; i--) {
backwards.push(temp[i]);
}
return backwards.join('').toString();
}
console.log(split("10 2 3 U S A"));
console.log(split("2345678910"));javascript algorithm
javascript algorithm
edited 10 hours ago
Pac0
7,70722545
7,70722545
asked 11 hours ago
user8107351user8107351
617
617
1
please format you code!
– MrSmith42
10 hours ago
1
OP wantsA S U 3 2 10if I understood correctly
– Pac0
10 hours ago
1
I added the other example mentioned above the snippet into it, as already two answers (mine deleted included) missed that one.
– Pac0
10 hours ago
1
Are we assuming that10is always together and in that order? If so, @OmG answer should be okay.
– Caleb Lucas
10 hours ago
1
What about the string USA101001 ? Should it give 101001ASU ?
– Pac0
10 hours ago
|
show 7 more comments
1
please format you code!
– MrSmith42
10 hours ago
1
OP wantsA S U 3 2 10if I understood correctly
– Pac0
10 hours ago
1
I added the other example mentioned above the snippet into it, as already two answers (mine deleted included) missed that one.
– Pac0
10 hours ago
1
Are we assuming that10is always together and in that order? If so, @OmG answer should be okay.
– Caleb Lucas
10 hours ago
1
What about the string USA101001 ? Should it give 101001ASU ?
– Pac0
10 hours ago
1
1
please format you code!
– MrSmith42
10 hours ago
please format you code!
– MrSmith42
10 hours ago
1
1
OP wants
A S U 3 2 10 if I understood correctly– Pac0
10 hours ago
OP wants
A S U 3 2 10 if I understood correctly– Pac0
10 hours ago
1
1
I added the other example mentioned above the snippet into it, as already two answers (mine deleted included) missed that one.
– Pac0
10 hours ago
I added the other example mentioned above the snippet into it, as already two answers (mine deleted included) missed that one.
– Pac0
10 hours ago
1
1
Are we assuming that
10 is always together and in that order? If so, @OmG answer should be okay.– Caleb Lucas
10 hours ago
Are we assuming that
10 is always together and in that order? If so, @OmG answer should be okay.– Caleb Lucas
10 hours ago
1
1
What about the string USA101001 ? Should it give 101001ASU ?
– Pac0
10 hours ago
What about the string USA101001 ? Should it give 101001ASU ?
– Pac0
10 hours ago
|
show 7 more comments
7 Answers
7
active
oldest
votes
You can replace 10 with a specified character which does not exist in the text, and after running the implemented algorithm replace it back with 10.
let out_of_alphabet_character = '#';
var reg_for_the_alphabet = new RegExp(out_of_alphabet_character, "g");
function specific_revert(str) {
str = str.replace(/(10)/g, out_of_alphabet_character);
let temp = ;
temp = str.split('');
const backwards = ;
const totalItems = str.length - 1;
for (let i = totalItems; i >= 0; i--) {
backwards.push(temp[i]);
}
return backwards.join('').toString().replace(reg_for_the_alphabet, '10');
}
console.log(specific_revert("10 2 3 U S A"));
console.log(specific_revert("234567891010"));
1
That would be the simplest (in term of understandability) way of doing that IMHO
– Pac0
10 hours ago
ha ! I think it fails for complex 10 strings like my example above : USA101001
– Pac0
10 hours ago
1
@Pac0 What should be the result forUSA101001?
– OmG
10 hours ago
We don't know yet, I presume. Need OP clarification. (but it works for both the examples given, at least)
– Pac0
10 hours ago
1
This would work, but extend it so it replaces the longest sequence of1and0characters, not just10.
– Amy
10 hours ago
add a comment |
Just check for the special case & code the normal logic or reversing as usual
const reverse = str => {
let rev = "";
for (let i = 0; i < str.length; i++) {
if (str[i] === '1' && i + 1 < str.length && str[i+1] === '0') {
rev = '10' + rev;
i++;
} else rev = str[i] + rev;
}
return rev;
}
console.log(reverse("10 2 3 U S A")); // returns A S U 3 2 10
console.log(reverse("2345678910")); // returns 1098765432
this code dose not work for console.log(reverse("234567891000000")) only uses for 2345678910
– mohammad javad ahmadi
10 hours ago
1
@mohammadjavadahmadi I am getting "000001098765432", which seems to be the correct value.
– Danyal Imran
10 hours ago
correct is 100000098765432
– mohammad javad ahmadi
10 hours ago
1
@mohammadjavadahmadi No it is not... that was not a condition in the question.
– Mr. Polywhirl
10 hours ago
3
OP said that he doesn't want to reverse 10, he doesn't say anything about how other values before or after 10 are affected. I don't know why would you even think that since its not even mentioned anywhere lol @mohammadjavadahmadi
– Danyal Imran
10 hours ago
|
show 3 more comments
You can reduce over the matched array from using a regular expression. It's more costly than a for/loop that concatenates strings, but it was fun figuring it out.
function split(str) {
const re = /([A-Z23456789 ]+)|(10)/g
return str.match(re).reduce((acc, c) => {
// if the match is 10 prepend it to the accumulator
// otherwise reverse the match and then prepend it
acc.unshift(c === '10' ? c : [...c].reverse().join(''));
return acc;
}, ).join('');
}
console.log(split('2345678910'));
console.log(split('10 2 3 U S A'));
console.log(split('2 3 U S A10'));add a comment |
You need some pre-conditions to check each character's value.
Due to the vagueness of the question, it is reasonable to believe that the number system that OP defines consists of [2, 3, 4, 5, 6, 7, 8, 9, 10] and all other characters A-Z (including 0 and 1) are simply characters.
String.prototype.isNumeric = function() {
return !isNaN(parseFloat(this)) && isFinite(this);
};
function reverse(str) {
let tokens = , len = str.length;
while (len--) {
let char = str.charAt(len);
if (char.isNumeric()) {
if (len > 0 && str.charAt(len - 1).isNumeric()) {
let curr = parseInt(char, 10),
next = parseInt(str.charAt(len - 1), 10);
if (curr === 0 && next === 1) {
tokens.push(10);
len--;
continue;
}
}
}
tokens.push(char);
}
return tokens.join('');
}
console.log(reverse("10 2 3 U S A"));
console.log(reverse('2345678910'));Output:
A S U 3 2 10
1098765432
for 'USA101001' it gives 11010, which looks wrong.
– Pac0
10 hours ago
Based on the original example: "e.g, 2345678910 would be 1098765432."
– Mr. Polywhirl
10 hours ago
my example is a bit complex, but OP gave at least an example with letters, 10 2 3 U S A
– Pac0
10 hours ago
Ok, I fixed it.
– Mr. Polywhirl
10 hours ago
this code dose not work for console.log(reverse("234567891000000")) only uses for 2345678910
– mohammad javad ahmadi
10 hours ago
|
show 3 more comments
Below is a recursive approach.
function f(s, i=0){
if (i == s.length)
return '';
if (['0', '1'].includes(s[i])){
let curr = s[i];
while (['0', '1'].includes(s[++i]))
curr += s[i]
return f(s, i) + curr;
}
return f(s, i + 1) + s[i];
}
console.log(f('10 2 3 U S A'));
console.log(f('2345678910'));
console.log(f('USA101001'));
Wouldn'tUSA101001be101010ASU?
– Mr. Polywhirl
10 hours ago
@Mr.Polywhirl I thought sequences of 1 and 0 were not to be reversed.
– elena a
10 hours ago
U S A 10 10 0 1→1 0 10 10 A S U→101010ASU
– Mr. Polywhirl
10 hours ago
@Mr.Polywhirl can you please show me where the OP indicated your interpretation is the correct one?
– elena a
10 hours ago
Due to the vagueness of the question, it is reasonable to believe that the number system is [2, 3, 4, 5, 6, 7, 8, 9, 10] and all other characters A-Z (including 0 and 1) are simply characters.
– Mr. Polywhirl
10 hours ago
|
show 6 more comments
Nice question so far.
You may try this recursive approach(if not changing 10 for other character not allowed):
function reverseKeepTen(str, arr = ) {
const tenIdx = str.indexOf('10');
if (!str.length) {
return arr.join('');
}
if (tenIdx === -1) {
return [...str.split('').reverse(), ...arr].join('');
} else {
const digitsBefore = str.slice(0, tenIdx);
const arrBefore = digitsBefore ? [...digitsBefore.split(''), 10].reverse() : [10];
return reverseKeepTen(str.slice(tenIdx + 2), [...arrBefore, ...arr])
}
};
console.log(reverseKeepTen('101234105678910')) // 109876510432110
console.log(reverseKeepTen('12341056789')) // 98765104321
console.log(reverseKeepTen('1012345')) // 5432110
console.log(reverseKeepTen('5678910')) // 1098765
console.log(reverseKeepTen('10111101')) // 11011110add a comment |
this code is worked for all type of string with zero :
function split(str) {
let temp = ,
bool = true;
temp = str.split('');
var backwards = ,
zeroBackward = ;
var totalItems = str.length - 1;
for (let i = totalItems; i >= 0; i--) {
if(temp[i] == '0' && i == totalItems) {
zeroBackward.push(temp[i]);
totalItems = totalItems -1;
} else if(temp[i] != '0' && bool) {
backwards.push(temp[i]);
backwards = backwards.concat(zeroBackward);
bool = false;
} else if(!bool) {
backwards.push(temp[i]);
}
}
return backwards.join('').toString();
}
console.log(split("10 2 3 U S A"));
console.log(split("2345678910"));
console.log(split("23456789100000"));
console.log(split("234567891000001"));
Why a negative score?
– mohammad javad ahmadi
10 hours ago
1
Not the downvoter, but it fails on the first example
– Pac0
9 hours ago
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54330189%2fhow-to-reverse-a-string-with-numbers-but-dont-reverse-1-and-0%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
7 Answers
7
active
oldest
votes
7 Answers
7
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can replace 10 with a specified character which does not exist in the text, and after running the implemented algorithm replace it back with 10.
let out_of_alphabet_character = '#';
var reg_for_the_alphabet = new RegExp(out_of_alphabet_character, "g");
function specific_revert(str) {
str = str.replace(/(10)/g, out_of_alphabet_character);
let temp = ;
temp = str.split('');
const backwards = ;
const totalItems = str.length - 1;
for (let i = totalItems; i >= 0; i--) {
backwards.push(temp[i]);
}
return backwards.join('').toString().replace(reg_for_the_alphabet, '10');
}
console.log(specific_revert("10 2 3 U S A"));
console.log(specific_revert("234567891010"));
1
That would be the simplest (in term of understandability) way of doing that IMHO
– Pac0
10 hours ago
ha ! I think it fails for complex 10 strings like my example above : USA101001
– Pac0
10 hours ago
1
@Pac0 What should be the result forUSA101001?
– OmG
10 hours ago
We don't know yet, I presume. Need OP clarification. (but it works for both the examples given, at least)
– Pac0
10 hours ago
1
This would work, but extend it so it replaces the longest sequence of1and0characters, not just10.
– Amy
10 hours ago
add a comment |
You can replace 10 with a specified character which does not exist in the text, and after running the implemented algorithm replace it back with 10.
let out_of_alphabet_character = '#';
var reg_for_the_alphabet = new RegExp(out_of_alphabet_character, "g");
function specific_revert(str) {
str = str.replace(/(10)/g, out_of_alphabet_character);
let temp = ;
temp = str.split('');
const backwards = ;
const totalItems = str.length - 1;
for (let i = totalItems; i >= 0; i--) {
backwards.push(temp[i]);
}
return backwards.join('').toString().replace(reg_for_the_alphabet, '10');
}
console.log(specific_revert("10 2 3 U S A"));
console.log(specific_revert("234567891010"));
1
That would be the simplest (in term of understandability) way of doing that IMHO
– Pac0
10 hours ago
ha ! I think it fails for complex 10 strings like my example above : USA101001
– Pac0
10 hours ago
1
@Pac0 What should be the result forUSA101001?
– OmG
10 hours ago
We don't know yet, I presume. Need OP clarification. (but it works for both the examples given, at least)
– Pac0
10 hours ago
1
This would work, but extend it so it replaces the longest sequence of1and0characters, not just10.
– Amy
10 hours ago
add a comment |
You can replace 10 with a specified character which does not exist in the text, and after running the implemented algorithm replace it back with 10.
let out_of_alphabet_character = '#';
var reg_for_the_alphabet = new RegExp(out_of_alphabet_character, "g");
function specific_revert(str) {
str = str.replace(/(10)/g, out_of_alphabet_character);
let temp = ;
temp = str.split('');
const backwards = ;
const totalItems = str.length - 1;
for (let i = totalItems; i >= 0; i--) {
backwards.push(temp[i]);
}
return backwards.join('').toString().replace(reg_for_the_alphabet, '10');
}
console.log(specific_revert("10 2 3 U S A"));
console.log(specific_revert("234567891010"));You can replace 10 with a specified character which does not exist in the text, and after running the implemented algorithm replace it back with 10.
let out_of_alphabet_character = '#';
var reg_for_the_alphabet = new RegExp(out_of_alphabet_character, "g");
function specific_revert(str) {
str = str.replace(/(10)/g, out_of_alphabet_character);
let temp = ;
temp = str.split('');
const backwards = ;
const totalItems = str.length - 1;
for (let i = totalItems; i >= 0; i--) {
backwards.push(temp[i]);
}
return backwards.join('').toString().replace(reg_for_the_alphabet, '10');
}
console.log(specific_revert("10 2 3 U S A"));
console.log(specific_revert("234567891010"));let out_of_alphabet_character = '#';
var reg_for_the_alphabet = new RegExp(out_of_alphabet_character, "g");
function specific_revert(str) {
str = str.replace(/(10)/g, out_of_alphabet_character);
let temp = ;
temp = str.split('');
const backwards = ;
const totalItems = str.length - 1;
for (let i = totalItems; i >= 0; i--) {
backwards.push(temp[i]);
}
return backwards.join('').toString().replace(reg_for_the_alphabet, '10');
}
console.log(specific_revert("10 2 3 U S A"));
console.log(specific_revert("234567891010"));let out_of_alphabet_character = '#';
var reg_for_the_alphabet = new RegExp(out_of_alphabet_character, "g");
function specific_revert(str) {
str = str.replace(/(10)/g, out_of_alphabet_character);
let temp = ;
temp = str.split('');
const backwards = ;
const totalItems = str.length - 1;
for (let i = totalItems; i >= 0; i--) {
backwards.push(temp[i]);
}
return backwards.join('').toString().replace(reg_for_the_alphabet, '10');
}
console.log(specific_revert("10 2 3 U S A"));
console.log(specific_revert("234567891010"));edited 10 hours ago
answered 10 hours ago
OmGOmG
8,08852844
8,08852844
1
That would be the simplest (in term of understandability) way of doing that IMHO
– Pac0
10 hours ago
ha ! I think it fails for complex 10 strings like my example above : USA101001
– Pac0
10 hours ago
1
@Pac0 What should be the result forUSA101001?
– OmG
10 hours ago
We don't know yet, I presume. Need OP clarification. (but it works for both the examples given, at least)
– Pac0
10 hours ago
1
This would work, but extend it so it replaces the longest sequence of1and0characters, not just10.
– Amy
10 hours ago
add a comment |
1
That would be the simplest (in term of understandability) way of doing that IMHO
– Pac0
10 hours ago
ha ! I think it fails for complex 10 strings like my example above : USA101001
– Pac0
10 hours ago
1
@Pac0 What should be the result forUSA101001?
– OmG
10 hours ago
We don't know yet, I presume. Need OP clarification. (but it works for both the examples given, at least)
– Pac0
10 hours ago
1
This would work, but extend it so it replaces the longest sequence of1and0characters, not just10.
– Amy
10 hours ago
1
1
That would be the simplest (in term of understandability) way of doing that IMHO
– Pac0
10 hours ago
That would be the simplest (in term of understandability) way of doing that IMHO
– Pac0
10 hours ago
ha ! I think it fails for complex 10 strings like my example above : USA101001
– Pac0
10 hours ago
ha ! I think it fails for complex 10 strings like my example above : USA101001
– Pac0
10 hours ago
1
1
@Pac0 What should be the result for
USA101001?– OmG
10 hours ago
@Pac0 What should be the result for
USA101001?– OmG
10 hours ago
We don't know yet, I presume. Need OP clarification. (but it works for both the examples given, at least)
– Pac0
10 hours ago
We don't know yet, I presume. Need OP clarification. (but it works for both the examples given, at least)
– Pac0
10 hours ago
1
1
This would work, but extend it so it replaces the longest sequence of
1 and 0 characters, not just 10.– Amy
10 hours ago
This would work, but extend it so it replaces the longest sequence of
1 and 0 characters, not just 10.– Amy
10 hours ago
add a comment |
Just check for the special case & code the normal logic or reversing as usual
const reverse = str => {
let rev = "";
for (let i = 0; i < str.length; i++) {
if (str[i] === '1' && i + 1 < str.length && str[i+1] === '0') {
rev = '10' + rev;
i++;
} else rev = str[i] + rev;
}
return rev;
}
console.log(reverse("10 2 3 U S A")); // returns A S U 3 2 10
console.log(reverse("2345678910")); // returns 1098765432
this code dose not work for console.log(reverse("234567891000000")) only uses for 2345678910
– mohammad javad ahmadi
10 hours ago
1
@mohammadjavadahmadi I am getting "000001098765432", which seems to be the correct value.
– Danyal Imran
10 hours ago
correct is 100000098765432
– mohammad javad ahmadi
10 hours ago
1
@mohammadjavadahmadi No it is not... that was not a condition in the question.
– Mr. Polywhirl
10 hours ago
3
OP said that he doesn't want to reverse 10, he doesn't say anything about how other values before or after 10 are affected. I don't know why would you even think that since its not even mentioned anywhere lol @mohammadjavadahmadi
– Danyal Imran
10 hours ago
|
show 3 more comments
Just check for the special case & code the normal logic or reversing as usual
const reverse = str => {
let rev = "";
for (let i = 0; i < str.length; i++) {
if (str[i] === '1' && i + 1 < str.length && str[i+1] === '0') {
rev = '10' + rev;
i++;
} else rev = str[i] + rev;
}
return rev;
}
console.log(reverse("10 2 3 U S A")); // returns A S U 3 2 10
console.log(reverse("2345678910")); // returns 1098765432
this code dose not work for console.log(reverse("234567891000000")) only uses for 2345678910
– mohammad javad ahmadi
10 hours ago
1
@mohammadjavadahmadi I am getting "000001098765432", which seems to be the correct value.
– Danyal Imran
10 hours ago
correct is 100000098765432
– mohammad javad ahmadi
10 hours ago
1
@mohammadjavadahmadi No it is not... that was not a condition in the question.
– Mr. Polywhirl
10 hours ago
3
OP said that he doesn't want to reverse 10, he doesn't say anything about how other values before or after 10 are affected. I don't know why would you even think that since its not even mentioned anywhere lol @mohammadjavadahmadi
– Danyal Imran
10 hours ago
|
show 3 more comments
Just check for the special case & code the normal logic or reversing as usual
const reverse = str => {
let rev = "";
for (let i = 0; i < str.length; i++) {
if (str[i] === '1' && i + 1 < str.length && str[i+1] === '0') {
rev = '10' + rev;
i++;
} else rev = str[i] + rev;
}
return rev;
}
console.log(reverse("10 2 3 U S A")); // returns A S U 3 2 10
console.log(reverse("2345678910")); // returns 1098765432Just check for the special case & code the normal logic or reversing as usual
const reverse = str => {
let rev = "";
for (let i = 0; i < str.length; i++) {
if (str[i] === '1' && i + 1 < str.length && str[i+1] === '0') {
rev = '10' + rev;
i++;
} else rev = str[i] + rev;
}
return rev;
}
console.log(reverse("10 2 3 U S A")); // returns A S U 3 2 10
console.log(reverse("2345678910")); // returns 1098765432 const reverse = str => {
let rev = "";
for (let i = 0; i < str.length; i++) {
if (str[i] === '1' && i + 1 < str.length && str[i+1] === '0') {
rev = '10' + rev;
i++;
} else rev = str[i] + rev;
}
return rev;
}
console.log(reverse("10 2 3 U S A")); // returns A S U 3 2 10
console.log(reverse("2345678910")); // returns 1098765432 const reverse = str => {
let rev = "";
for (let i = 0; i < str.length; i++) {
if (str[i] === '1' && i + 1 < str.length && str[i+1] === '0') {
rev = '10' + rev;
i++;
} else rev = str[i] + rev;
}
return rev;
}
console.log(reverse("10 2 3 U S A")); // returns A S U 3 2 10
console.log(reverse("2345678910")); // returns 1098765432edited 10 hours ago
Pac0
7,70722545
7,70722545
answered 10 hours ago
Danyal ImranDanyal Imran
955214
955214
this code dose not work for console.log(reverse("234567891000000")) only uses for 2345678910
– mohammad javad ahmadi
10 hours ago
1
@mohammadjavadahmadi I am getting "000001098765432", which seems to be the correct value.
– Danyal Imran
10 hours ago
correct is 100000098765432
– mohammad javad ahmadi
10 hours ago
1
@mohammadjavadahmadi No it is not... that was not a condition in the question.
– Mr. Polywhirl
10 hours ago
3
OP said that he doesn't want to reverse 10, he doesn't say anything about how other values before or after 10 are affected. I don't know why would you even think that since its not even mentioned anywhere lol @mohammadjavadahmadi
– Danyal Imran
10 hours ago
|
show 3 more comments
this code dose not work for console.log(reverse("234567891000000")) only uses for 2345678910
– mohammad javad ahmadi
10 hours ago
1
@mohammadjavadahmadi I am getting "000001098765432", which seems to be the correct value.
– Danyal Imran
10 hours ago
correct is 100000098765432
– mohammad javad ahmadi
10 hours ago
1
@mohammadjavadahmadi No it is not... that was not a condition in the question.
– Mr. Polywhirl
10 hours ago
3
OP said that he doesn't want to reverse 10, he doesn't say anything about how other values before or after 10 are affected. I don't know why would you even think that since its not even mentioned anywhere lol @mohammadjavadahmadi
– Danyal Imran
10 hours ago
this code dose not work for console.log(reverse("234567891000000")) only uses for 2345678910
– mohammad javad ahmadi
10 hours ago
this code dose not work for console.log(reverse("234567891000000")) only uses for 2345678910
– mohammad javad ahmadi
10 hours ago
1
1
@mohammadjavadahmadi I am getting "000001098765432", which seems to be the correct value.
– Danyal Imran
10 hours ago
@mohammadjavadahmadi I am getting "000001098765432", which seems to be the correct value.
– Danyal Imran
10 hours ago
correct is 100000098765432
– mohammad javad ahmadi
10 hours ago
correct is 100000098765432
– mohammad javad ahmadi
10 hours ago
1
1
@mohammadjavadahmadi No it is not... that was not a condition in the question.
– Mr. Polywhirl
10 hours ago
@mohammadjavadahmadi No it is not... that was not a condition in the question.
– Mr. Polywhirl
10 hours ago
3
3
OP said that he doesn't want to reverse 10, he doesn't say anything about how other values before or after 10 are affected. I don't know why would you even think that since its not even mentioned anywhere lol @mohammadjavadahmadi
– Danyal Imran
10 hours ago
OP said that he doesn't want to reverse 10, he doesn't say anything about how other values before or after 10 are affected. I don't know why would you even think that since its not even mentioned anywhere lol @mohammadjavadahmadi
– Danyal Imran
10 hours ago
|
show 3 more comments
You can reduce over the matched array from using a regular expression. It's more costly than a for/loop that concatenates strings, but it was fun figuring it out.
function split(str) {
const re = /([A-Z23456789 ]+)|(10)/g
return str.match(re).reduce((acc, c) => {
// if the match is 10 prepend it to the accumulator
// otherwise reverse the match and then prepend it
acc.unshift(c === '10' ? c : [...c].reverse().join(''));
return acc;
}, ).join('');
}
console.log(split('2345678910'));
console.log(split('10 2 3 U S A'));
console.log(split('2 3 U S A10'));add a comment |
You can reduce over the matched array from using a regular expression. It's more costly than a for/loop that concatenates strings, but it was fun figuring it out.
function split(str) {
const re = /([A-Z23456789 ]+)|(10)/g
return str.match(re).reduce((acc, c) => {
// if the match is 10 prepend it to the accumulator
// otherwise reverse the match and then prepend it
acc.unshift(c === '10' ? c : [...c].reverse().join(''));
return acc;
}, ).join('');
}
console.log(split('2345678910'));
console.log(split('10 2 3 U S A'));
console.log(split('2 3 U S A10'));add a comment |
You can reduce over the matched array from using a regular expression. It's more costly than a for/loop that concatenates strings, but it was fun figuring it out.
function split(str) {
const re = /([A-Z23456789 ]+)|(10)/g
return str.match(re).reduce((acc, c) => {
// if the match is 10 prepend it to the accumulator
// otherwise reverse the match and then prepend it
acc.unshift(c === '10' ? c : [...c].reverse().join(''));
return acc;
}, ).join('');
}
console.log(split('2345678910'));
console.log(split('10 2 3 U S A'));
console.log(split('2 3 U S A10'));You can reduce over the matched array from using a regular expression. It's more costly than a for/loop that concatenates strings, but it was fun figuring it out.
function split(str) {
const re = /([A-Z23456789 ]+)|(10)/g
return str.match(re).reduce((acc, c) => {
// if the match is 10 prepend it to the accumulator
// otherwise reverse the match and then prepend it
acc.unshift(c === '10' ? c : [...c].reverse().join(''));
return acc;
}, ).join('');
}
console.log(split('2345678910'));
console.log(split('10 2 3 U S A'));
console.log(split('2 3 U S A10'));function split(str) {
const re = /([A-Z23456789 ]+)|(10)/g
return str.match(re).reduce((acc, c) => {
// if the match is 10 prepend it to the accumulator
// otherwise reverse the match and then prepend it
acc.unshift(c === '10' ? c : [...c].reverse().join(''));
return acc;
}, ).join('');
}
console.log(split('2345678910'));
console.log(split('10 2 3 U S A'));
console.log(split('2 3 U S A10'));function split(str) {
const re = /([A-Z23456789 ]+)|(10)/g
return str.match(re).reduce((acc, c) => {
// if the match is 10 prepend it to the accumulator
// otherwise reverse the match and then prepend it
acc.unshift(c === '10' ? c : [...c].reverse().join(''));
return acc;
}, ).join('');
}
console.log(split('2345678910'));
console.log(split('10 2 3 U S A'));
console.log(split('2 3 U S A10'));edited 9 hours ago
answered 10 hours ago
AndyAndy
29.5k73462
29.5k73462
add a comment |
add a comment |
You need some pre-conditions to check each character's value.
Due to the vagueness of the question, it is reasonable to believe that the number system that OP defines consists of [2, 3, 4, 5, 6, 7, 8, 9, 10] and all other characters A-Z (including 0 and 1) are simply characters.
String.prototype.isNumeric = function() {
return !isNaN(parseFloat(this)) && isFinite(this);
};
function reverse(str) {
let tokens = , len = str.length;
while (len--) {
let char = str.charAt(len);
if (char.isNumeric()) {
if (len > 0 && str.charAt(len - 1).isNumeric()) {
let curr = parseInt(char, 10),
next = parseInt(str.charAt(len - 1), 10);
if (curr === 0 && next === 1) {
tokens.push(10);
len--;
continue;
}
}
}
tokens.push(char);
}
return tokens.join('');
}
console.log(reverse("10 2 3 U S A"));
console.log(reverse('2345678910'));Output:
A S U 3 2 10
1098765432
for 'USA101001' it gives 11010, which looks wrong.
– Pac0
10 hours ago
Based on the original example: "e.g, 2345678910 would be 1098765432."
– Mr. Polywhirl
10 hours ago
my example is a bit complex, but OP gave at least an example with letters, 10 2 3 U S A
– Pac0
10 hours ago
Ok, I fixed it.
– Mr. Polywhirl
10 hours ago
this code dose not work for console.log(reverse("234567891000000")) only uses for 2345678910
– mohammad javad ahmadi
10 hours ago
|
show 3 more comments
You need some pre-conditions to check each character's value.
Due to the vagueness of the question, it is reasonable to believe that the number system that OP defines consists of [2, 3, 4, 5, 6, 7, 8, 9, 10] and all other characters A-Z (including 0 and 1) are simply characters.
String.prototype.isNumeric = function() {
return !isNaN(parseFloat(this)) && isFinite(this);
};
function reverse(str) {
let tokens = , len = str.length;
while (len--) {
let char = str.charAt(len);
if (char.isNumeric()) {
if (len > 0 && str.charAt(len - 1).isNumeric()) {
let curr = parseInt(char, 10),
next = parseInt(str.charAt(len - 1), 10);
if (curr === 0 && next === 1) {
tokens.push(10);
len--;
continue;
}
}
}
tokens.push(char);
}
return tokens.join('');
}
console.log(reverse("10 2 3 U S A"));
console.log(reverse('2345678910'));Output:
A S U 3 2 10
1098765432
for 'USA101001' it gives 11010, which looks wrong.
– Pac0
10 hours ago
Based on the original example: "e.g, 2345678910 would be 1098765432."
– Mr. Polywhirl
10 hours ago
my example is a bit complex, but OP gave at least an example with letters, 10 2 3 U S A
– Pac0
10 hours ago
Ok, I fixed it.
– Mr. Polywhirl
10 hours ago
this code dose not work for console.log(reverse("234567891000000")) only uses for 2345678910
– mohammad javad ahmadi
10 hours ago
|
show 3 more comments
You need some pre-conditions to check each character's value.
Due to the vagueness of the question, it is reasonable to believe that the number system that OP defines consists of [2, 3, 4, 5, 6, 7, 8, 9, 10] and all other characters A-Z (including 0 and 1) are simply characters.
String.prototype.isNumeric = function() {
return !isNaN(parseFloat(this)) && isFinite(this);
};
function reverse(str) {
let tokens = , len = str.length;
while (len--) {
let char = str.charAt(len);
if (char.isNumeric()) {
if (len > 0 && str.charAt(len - 1).isNumeric()) {
let curr = parseInt(char, 10),
next = parseInt(str.charAt(len - 1), 10);
if (curr === 0 && next === 1) {
tokens.push(10);
len--;
continue;
}
}
}
tokens.push(char);
}
return tokens.join('');
}
console.log(reverse("10 2 3 U S A"));
console.log(reverse('2345678910'));Output:
A S U 3 2 10
1098765432
You need some pre-conditions to check each character's value.
Due to the vagueness of the question, it is reasonable to believe that the number system that OP defines consists of [2, 3, 4, 5, 6, 7, 8, 9, 10] and all other characters A-Z (including 0 and 1) are simply characters.
String.prototype.isNumeric = function() {
return !isNaN(parseFloat(this)) && isFinite(this);
};
function reverse(str) {
let tokens = , len = str.length;
while (len--) {
let char = str.charAt(len);
if (char.isNumeric()) {
if (len > 0 && str.charAt(len - 1).isNumeric()) {
let curr = parseInt(char, 10),
next = parseInt(str.charAt(len - 1), 10);
if (curr === 0 && next === 1) {
tokens.push(10);
len--;
continue;
}
}
}
tokens.push(char);
}
return tokens.join('');
}
console.log(reverse("10 2 3 U S A"));
console.log(reverse('2345678910'));Output:
A S U 3 2 10
1098765432
String.prototype.isNumeric = function() {
return !isNaN(parseFloat(this)) && isFinite(this);
};
function reverse(str) {
let tokens = , len = str.length;
while (len--) {
let char = str.charAt(len);
if (char.isNumeric()) {
if (len > 0 && str.charAt(len - 1).isNumeric()) {
let curr = parseInt(char, 10),
next = parseInt(str.charAt(len - 1), 10);
if (curr === 0 && next === 1) {
tokens.push(10);
len--;
continue;
}
}
}
tokens.push(char);
}
return tokens.join('');
}
console.log(reverse("10 2 3 U S A"));
console.log(reverse('2345678910'));String.prototype.isNumeric = function() {
return !isNaN(parseFloat(this)) && isFinite(this);
};
function reverse(str) {
let tokens = , len = str.length;
while (len--) {
let char = str.charAt(len);
if (char.isNumeric()) {
if (len > 0 && str.charAt(len - 1).isNumeric()) {
let curr = parseInt(char, 10),
next = parseInt(str.charAt(len - 1), 10);
if (curr === 0 && next === 1) {
tokens.push(10);
len--;
continue;
}
}
}
tokens.push(char);
}
return tokens.join('');
}
console.log(reverse("10 2 3 U S A"));
console.log(reverse('2345678910'));edited 10 hours ago
answered 10 hours ago
Mr. PolywhirlMr. Polywhirl
16.6k84886
16.6k84886
for 'USA101001' it gives 11010, which looks wrong.
– Pac0
10 hours ago
Based on the original example: "e.g, 2345678910 would be 1098765432."
– Mr. Polywhirl
10 hours ago
my example is a bit complex, but OP gave at least an example with letters, 10 2 3 U S A
– Pac0
10 hours ago
Ok, I fixed it.
– Mr. Polywhirl
10 hours ago
this code dose not work for console.log(reverse("234567891000000")) only uses for 2345678910
– mohammad javad ahmadi
10 hours ago
|
show 3 more comments
for 'USA101001' it gives 11010, which looks wrong.
– Pac0
10 hours ago
Based on the original example: "e.g, 2345678910 would be 1098765432."
– Mr. Polywhirl
10 hours ago
my example is a bit complex, but OP gave at least an example with letters, 10 2 3 U S A
– Pac0
10 hours ago
Ok, I fixed it.
– Mr. Polywhirl
10 hours ago
this code dose not work for console.log(reverse("234567891000000")) only uses for 2345678910
– mohammad javad ahmadi
10 hours ago
for 'USA101001' it gives 11010, which looks wrong.
– Pac0
10 hours ago
for 'USA101001' it gives 11010, which looks wrong.
– Pac0
10 hours ago
Based on the original example: "e.g, 2345678910 would be 1098765432."
– Mr. Polywhirl
10 hours ago
Based on the original example: "e.g, 2345678910 would be 1098765432."
– Mr. Polywhirl
10 hours ago
my example is a bit complex, but OP gave at least an example with letters, 10 2 3 U S A
– Pac0
10 hours ago
my example is a bit complex, but OP gave at least an example with letters, 10 2 3 U S A
– Pac0
10 hours ago
Ok, I fixed it.
– Mr. Polywhirl
10 hours ago
Ok, I fixed it.
– Mr. Polywhirl
10 hours ago
this code dose not work for console.log(reverse("234567891000000")) only uses for 2345678910
– mohammad javad ahmadi
10 hours ago
this code dose not work for console.log(reverse("234567891000000")) only uses for 2345678910
– mohammad javad ahmadi
10 hours ago
|
show 3 more comments
Below is a recursive approach.
function f(s, i=0){
if (i == s.length)
return '';
if (['0', '1'].includes(s[i])){
let curr = s[i];
while (['0', '1'].includes(s[++i]))
curr += s[i]
return f(s, i) + curr;
}
return f(s, i + 1) + s[i];
}
console.log(f('10 2 3 U S A'));
console.log(f('2345678910'));
console.log(f('USA101001'));
Wouldn'tUSA101001be101010ASU?
– Mr. Polywhirl
10 hours ago
@Mr.Polywhirl I thought sequences of 1 and 0 were not to be reversed.
– elena a
10 hours ago
U S A 10 10 0 1→1 0 10 10 A S U→101010ASU
– Mr. Polywhirl
10 hours ago
@Mr.Polywhirl can you please show me where the OP indicated your interpretation is the correct one?
– elena a
10 hours ago
Due to the vagueness of the question, it is reasonable to believe that the number system is [2, 3, 4, 5, 6, 7, 8, 9, 10] and all other characters A-Z (including 0 and 1) are simply characters.
– Mr. Polywhirl
10 hours ago
|
show 6 more comments
Below is a recursive approach.
function f(s, i=0){
if (i == s.length)
return '';
if (['0', '1'].includes(s[i])){
let curr = s[i];
while (['0', '1'].includes(s[++i]))
curr += s[i]
return f(s, i) + curr;
}
return f(s, i + 1) + s[i];
}
console.log(f('10 2 3 U S A'));
console.log(f('2345678910'));
console.log(f('USA101001'));
Wouldn'tUSA101001be101010ASU?
– Mr. Polywhirl
10 hours ago
@Mr.Polywhirl I thought sequences of 1 and 0 were not to be reversed.
– elena a
10 hours ago
U S A 10 10 0 1→1 0 10 10 A S U→101010ASU
– Mr. Polywhirl
10 hours ago
@Mr.Polywhirl can you please show me where the OP indicated your interpretation is the correct one?
– elena a
10 hours ago
Due to the vagueness of the question, it is reasonable to believe that the number system is [2, 3, 4, 5, 6, 7, 8, 9, 10] and all other characters A-Z (including 0 and 1) are simply characters.
– Mr. Polywhirl
10 hours ago
|
show 6 more comments
Below is a recursive approach.
function f(s, i=0){
if (i == s.length)
return '';
if (['0', '1'].includes(s[i])){
let curr = s[i];
while (['0', '1'].includes(s[++i]))
curr += s[i]
return f(s, i) + curr;
}
return f(s, i + 1) + s[i];
}
console.log(f('10 2 3 U S A'));
console.log(f('2345678910'));
console.log(f('USA101001'));Below is a recursive approach.
function f(s, i=0){
if (i == s.length)
return '';
if (['0', '1'].includes(s[i])){
let curr = s[i];
while (['0', '1'].includes(s[++i]))
curr += s[i]
return f(s, i) + curr;
}
return f(s, i + 1) + s[i];
}
console.log(f('10 2 3 U S A'));
console.log(f('2345678910'));
console.log(f('USA101001'));function f(s, i=0){
if (i == s.length)
return '';
if (['0', '1'].includes(s[i])){
let curr = s[i];
while (['0', '1'].includes(s[++i]))
curr += s[i]
return f(s, i) + curr;
}
return f(s, i + 1) + s[i];
}
console.log(f('10 2 3 U S A'));
console.log(f('2345678910'));
console.log(f('USA101001'));function f(s, i=0){
if (i == s.length)
return '';
if (['0', '1'].includes(s[i])){
let curr = s[i];
while (['0', '1'].includes(s[++i]))
curr += s[i]
return f(s, i) + curr;
}
return f(s, i + 1) + s[i];
}
console.log(f('10 2 3 U S A'));
console.log(f('2345678910'));
console.log(f('USA101001'));edited 8 hours ago
answered 10 hours ago
elena aelena a
764
764
Wouldn'tUSA101001be101010ASU?
– Mr. Polywhirl
10 hours ago
@Mr.Polywhirl I thought sequences of 1 and 0 were not to be reversed.
– elena a
10 hours ago
U S A 10 10 0 1→1 0 10 10 A S U→101010ASU
– Mr. Polywhirl
10 hours ago
@Mr.Polywhirl can you please show me where the OP indicated your interpretation is the correct one?
– elena a
10 hours ago
Due to the vagueness of the question, it is reasonable to believe that the number system is [2, 3, 4, 5, 6, 7, 8, 9, 10] and all other characters A-Z (including 0 and 1) are simply characters.
– Mr. Polywhirl
10 hours ago
|
show 6 more comments
Wouldn'tUSA101001be101010ASU?
– Mr. Polywhirl
10 hours ago
@Mr.Polywhirl I thought sequences of 1 and 0 were not to be reversed.
– elena a
10 hours ago
U S A 10 10 0 1→1 0 10 10 A S U→101010ASU
– Mr. Polywhirl
10 hours ago
@Mr.Polywhirl can you please show me where the OP indicated your interpretation is the correct one?
– elena a
10 hours ago
Due to the vagueness of the question, it is reasonable to believe that the number system is [2, 3, 4, 5, 6, 7, 8, 9, 10] and all other characters A-Z (including 0 and 1) are simply characters.
– Mr. Polywhirl
10 hours ago
Wouldn't
USA101001 be 101010ASU ?– Mr. Polywhirl
10 hours ago
Wouldn't
USA101001 be 101010ASU ?– Mr. Polywhirl
10 hours ago
@Mr.Polywhirl I thought sequences of 1 and 0 were not to be reversed.
– elena a
10 hours ago
@Mr.Polywhirl I thought sequences of 1 and 0 were not to be reversed.
– elena a
10 hours ago
U S A 10 10 0 1→ 1 0 10 10 A S U → 101010ASU– Mr. Polywhirl
10 hours ago
U S A 10 10 0 1→ 1 0 10 10 A S U → 101010ASU– Mr. Polywhirl
10 hours ago
@Mr.Polywhirl can you please show me where the OP indicated your interpretation is the correct one?
– elena a
10 hours ago
@Mr.Polywhirl can you please show me where the OP indicated your interpretation is the correct one?
– elena a
10 hours ago
Due to the vagueness of the question, it is reasonable to believe that the number system is [2, 3, 4, 5, 6, 7, 8, 9, 10] and all other characters A-Z (including 0 and 1) are simply characters.
– Mr. Polywhirl
10 hours ago
Due to the vagueness of the question, it is reasonable to believe that the number system is [2, 3, 4, 5, 6, 7, 8, 9, 10] and all other characters A-Z (including 0 and 1) are simply characters.
– Mr. Polywhirl
10 hours ago
|
show 6 more comments
Nice question so far.
You may try this recursive approach(if not changing 10 for other character not allowed):
function reverseKeepTen(str, arr = ) {
const tenIdx = str.indexOf('10');
if (!str.length) {
return arr.join('');
}
if (tenIdx === -1) {
return [...str.split('').reverse(), ...arr].join('');
} else {
const digitsBefore = str.slice(0, tenIdx);
const arrBefore = digitsBefore ? [...digitsBefore.split(''), 10].reverse() : [10];
return reverseKeepTen(str.slice(tenIdx + 2), [...arrBefore, ...arr])
}
};
console.log(reverseKeepTen('101234105678910')) // 109876510432110
console.log(reverseKeepTen('12341056789')) // 98765104321
console.log(reverseKeepTen('1012345')) // 5432110
console.log(reverseKeepTen('5678910')) // 1098765
console.log(reverseKeepTen('10111101')) // 11011110add a comment |
Nice question so far.
You may try this recursive approach(if not changing 10 for other character not allowed):
function reverseKeepTen(str, arr = ) {
const tenIdx = str.indexOf('10');
if (!str.length) {
return arr.join('');
}
if (tenIdx === -1) {
return [...str.split('').reverse(), ...arr].join('');
} else {
const digitsBefore = str.slice(0, tenIdx);
const arrBefore = digitsBefore ? [...digitsBefore.split(''), 10].reverse() : [10];
return reverseKeepTen(str.slice(tenIdx + 2), [...arrBefore, ...arr])
}
};
console.log(reverseKeepTen('101234105678910')) // 109876510432110
console.log(reverseKeepTen('12341056789')) // 98765104321
console.log(reverseKeepTen('1012345')) // 5432110
console.log(reverseKeepTen('5678910')) // 1098765
console.log(reverseKeepTen('10111101')) // 11011110add a comment |
Nice question so far.
You may try this recursive approach(if not changing 10 for other character not allowed):
function reverseKeepTen(str, arr = ) {
const tenIdx = str.indexOf('10');
if (!str.length) {
return arr.join('');
}
if (tenIdx === -1) {
return [...str.split('').reverse(), ...arr].join('');
} else {
const digitsBefore = str.slice(0, tenIdx);
const arrBefore = digitsBefore ? [...digitsBefore.split(''), 10].reverse() : [10];
return reverseKeepTen(str.slice(tenIdx + 2), [...arrBefore, ...arr])
}
};
console.log(reverseKeepTen('101234105678910')) // 109876510432110
console.log(reverseKeepTen('12341056789')) // 98765104321
console.log(reverseKeepTen('1012345')) // 5432110
console.log(reverseKeepTen('5678910')) // 1098765
console.log(reverseKeepTen('10111101')) // 11011110Nice question so far.
You may try this recursive approach(if not changing 10 for other character not allowed):
function reverseKeepTen(str, arr = ) {
const tenIdx = str.indexOf('10');
if (!str.length) {
return arr.join('');
}
if (tenIdx === -1) {
return [...str.split('').reverse(), ...arr].join('');
} else {
const digitsBefore = str.slice(0, tenIdx);
const arrBefore = digitsBefore ? [...digitsBefore.split(''), 10].reverse() : [10];
return reverseKeepTen(str.slice(tenIdx + 2), [...arrBefore, ...arr])
}
};
console.log(reverseKeepTen('101234105678910')) // 109876510432110
console.log(reverseKeepTen('12341056789')) // 98765104321
console.log(reverseKeepTen('1012345')) // 5432110
console.log(reverseKeepTen('5678910')) // 1098765
console.log(reverseKeepTen('10111101')) // 11011110function reverseKeepTen(str, arr = ) {
const tenIdx = str.indexOf('10');
if (!str.length) {
return arr.join('');
}
if (tenIdx === -1) {
return [...str.split('').reverse(), ...arr].join('');
} else {
const digitsBefore = str.slice(0, tenIdx);
const arrBefore = digitsBefore ? [...digitsBefore.split(''), 10].reverse() : [10];
return reverseKeepTen(str.slice(tenIdx + 2), [...arrBefore, ...arr])
}
};
console.log(reverseKeepTen('101234105678910')) // 109876510432110
console.log(reverseKeepTen('12341056789')) // 98765104321
console.log(reverseKeepTen('1012345')) // 5432110
console.log(reverseKeepTen('5678910')) // 1098765
console.log(reverseKeepTen('10111101')) // 11011110function reverseKeepTen(str, arr = ) {
const tenIdx = str.indexOf('10');
if (!str.length) {
return arr.join('');
}
if (tenIdx === -1) {
return [...str.split('').reverse(), ...arr].join('');
} else {
const digitsBefore = str.slice(0, tenIdx);
const arrBefore = digitsBefore ? [...digitsBefore.split(''), 10].reverse() : [10];
return reverseKeepTen(str.slice(tenIdx + 2), [...arrBefore, ...arr])
}
};
console.log(reverseKeepTen('101234105678910')) // 109876510432110
console.log(reverseKeepTen('12341056789')) // 98765104321
console.log(reverseKeepTen('1012345')) // 5432110
console.log(reverseKeepTen('5678910')) // 1098765
console.log(reverseKeepTen('10111101')) // 11011110edited 10 hours ago
answered 10 hours ago
Shevchenko ViktorShevchenko Viktor
797515
797515
add a comment |
add a comment |
this code is worked for all type of string with zero :
function split(str) {
let temp = ,
bool = true;
temp = str.split('');
var backwards = ,
zeroBackward = ;
var totalItems = str.length - 1;
for (let i = totalItems; i >= 0; i--) {
if(temp[i] == '0' && i == totalItems) {
zeroBackward.push(temp[i]);
totalItems = totalItems -1;
} else if(temp[i] != '0' && bool) {
backwards.push(temp[i]);
backwards = backwards.concat(zeroBackward);
bool = false;
} else if(!bool) {
backwards.push(temp[i]);
}
}
return backwards.join('').toString();
}
console.log(split("10 2 3 U S A"));
console.log(split("2345678910"));
console.log(split("23456789100000"));
console.log(split("234567891000001"));
Why a negative score?
– mohammad javad ahmadi
10 hours ago
1
Not the downvoter, but it fails on the first example
– Pac0
9 hours ago
add a comment |
this code is worked for all type of string with zero :
function split(str) {
let temp = ,
bool = true;
temp = str.split('');
var backwards = ,
zeroBackward = ;
var totalItems = str.length - 1;
for (let i = totalItems; i >= 0; i--) {
if(temp[i] == '0' && i == totalItems) {
zeroBackward.push(temp[i]);
totalItems = totalItems -1;
} else if(temp[i] != '0' && bool) {
backwards.push(temp[i]);
backwards = backwards.concat(zeroBackward);
bool = false;
} else if(!bool) {
backwards.push(temp[i]);
}
}
return backwards.join('').toString();
}
console.log(split("10 2 3 U S A"));
console.log(split("2345678910"));
console.log(split("23456789100000"));
console.log(split("234567891000001"));
Why a negative score?
– mohammad javad ahmadi
10 hours ago
1
Not the downvoter, but it fails on the first example
– Pac0
9 hours ago
add a comment |
this code is worked for all type of string with zero :
function split(str) {
let temp = ,
bool = true;
temp = str.split('');
var backwards = ,
zeroBackward = ;
var totalItems = str.length - 1;
for (let i = totalItems; i >= 0; i--) {
if(temp[i] == '0' && i == totalItems) {
zeroBackward.push(temp[i]);
totalItems = totalItems -1;
} else if(temp[i] != '0' && bool) {
backwards.push(temp[i]);
backwards = backwards.concat(zeroBackward);
bool = false;
} else if(!bool) {
backwards.push(temp[i]);
}
}
return backwards.join('').toString();
}
console.log(split("10 2 3 U S A"));
console.log(split("2345678910"));
console.log(split("23456789100000"));
console.log(split("234567891000001"));this code is worked for all type of string with zero :
function split(str) {
let temp = ,
bool = true;
temp = str.split('');
var backwards = ,
zeroBackward = ;
var totalItems = str.length - 1;
for (let i = totalItems; i >= 0; i--) {
if(temp[i] == '0' && i == totalItems) {
zeroBackward.push(temp[i]);
totalItems = totalItems -1;
} else if(temp[i] != '0' && bool) {
backwards.push(temp[i]);
backwards = backwards.concat(zeroBackward);
bool = false;
} else if(!bool) {
backwards.push(temp[i]);
}
}
return backwards.join('').toString();
}
console.log(split("10 2 3 U S A"));
console.log(split("2345678910"));
console.log(split("23456789100000"));
console.log(split("234567891000001"));function split(str) {
let temp = ,
bool = true;
temp = str.split('');
var backwards = ,
zeroBackward = ;
var totalItems = str.length - 1;
for (let i = totalItems; i >= 0; i--) {
if(temp[i] == '0' && i == totalItems) {
zeroBackward.push(temp[i]);
totalItems = totalItems -1;
} else if(temp[i] != '0' && bool) {
backwards.push(temp[i]);
backwards = backwards.concat(zeroBackward);
bool = false;
} else if(!bool) {
backwards.push(temp[i]);
}
}
return backwards.join('').toString();
}
console.log(split("10 2 3 U S A"));
console.log(split("2345678910"));
console.log(split("23456789100000"));
console.log(split("234567891000001"));function split(str) {
let temp = ,
bool = true;
temp = str.split('');
var backwards = ,
zeroBackward = ;
var totalItems = str.length - 1;
for (let i = totalItems; i >= 0; i--) {
if(temp[i] == '0' && i == totalItems) {
zeroBackward.push(temp[i]);
totalItems = totalItems -1;
} else if(temp[i] != '0' && bool) {
backwards.push(temp[i]);
backwards = backwards.concat(zeroBackward);
bool = false;
} else if(!bool) {
backwards.push(temp[i]);
}
}
return backwards.join('').toString();
}
console.log(split("10 2 3 U S A"));
console.log(split("2345678910"));
console.log(split("23456789100000"));
console.log(split("234567891000001"));edited 10 hours ago
answered 10 hours ago
mohammad javad ahmadimohammad javad ahmadi
1389
1389
Why a negative score?
– mohammad javad ahmadi
10 hours ago
1
Not the downvoter, but it fails on the first example
– Pac0
9 hours ago
add a comment |
Why a negative score?
– mohammad javad ahmadi
10 hours ago
1
Not the downvoter, but it fails on the first example
– Pac0
9 hours ago
Why a negative score?
– mohammad javad ahmadi
10 hours ago
Why a negative score?
– mohammad javad ahmadi
10 hours ago
1
1
Not the downvoter, but it fails on the first example
– Pac0
9 hours ago
Not the downvoter, but it fails on the first example
– Pac0
9 hours ago
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54330189%2fhow-to-reverse-a-string-with-numbers-but-dont-reverse-1-and-0%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
please format you code!
– MrSmith42
10 hours ago
1
OP wants
A S U 3 2 10if I understood correctly– Pac0
10 hours ago
1
I added the other example mentioned above the snippet into it, as already two answers (mine deleted included) missed that one.
– Pac0
10 hours ago
1
Are we assuming that
10is always together and in that order? If so, @OmG answer should be okay.– Caleb Lucas
10 hours ago
1
What about the string USA101001 ? Should it give 101001ASU ?
– Pac0
10 hours ago