Leetcode
#1 #easy #javascript
Two Sum
https://leetcode.com/problems/two-sum/description/
#1 #easy #javascript
Two Sum
https://leetcode.com/problems/two-sum/description/
var twoSum = function (nums, target) {
let finalArr = [];
for (let i = 0; i <= nums.length; i++) {
for (let y = i + 1; y <= nums.length; y++) {
if (nums[i] + nums[y] == target) {
finalArr.push(i);
finalArr.push(y);
}
}
}
return finalArr;
};LeetCode
Two Sum - LeetCode
Can you solve this real interview question? Two Sum - Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not…
You may assume that each input would have exactly one solution, and you may not…
#easy #javascript
Roman to Integer
https://leetcode.com/problems/roman-to-integer/description/
My solution:
Chatgpt:
Roman to Integer
https://leetcode.com/problems/roman-to-integer/description/
My solution:
var romanToInt = function (s) {
let sum = 0;
for (let i = 0; i < s.length; i++) {
if (s[i] == "I") {
if (s[i + 1] == "V") {
sum += 4;
i++;
} else if (s[i + 1] == "X") {
sum += 9;
i++;
} else {
sum++;
}
} else if (s[i] == "X") {
if (s[i + 1] == "L") {
sum += 40;
i++;
} else if (s[i + 1] == "C") {
sum += 90;
i++;
} else {
sum += 10;
}
} else if (s[i] == "C") {
if (s[i + 1] == "D") {
sum += 400;
i++;
} else if (s[i + 1] == "M") {
sum += 900;
i++;
} else {
sum += 100;
}
} else if (s[i] == "M") {
sum += 1000;
} else if (s[i] == "V") {
sum += 5;
} else if (s[i] == "L") {
sum += 50;
} else if (s[i] == "D") {
sum += 500;
}
}
return sum;
};Chatgpt:
var romanToInt = function(s) {
const romanMap = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
};
let sum = 0;
for (let i = 0; i < s.length; i++) {
if (i < s.length - 1 && romanMap[s[i]] < romanMap[s[i + 1]]) {
sum -= romanMap[s[i]];
} else {
sum += romanMap[s[i]];
}
}
return sum;
};LeetCode
Roman to Integer - LeetCode
Can you solve this real interview question? Roman to Integer - Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D …
Symbol Value
I 1
V 5
X 10
L 50
C 100
D …