Skip to content

Instantly share code, notes, and snippets.

@Ancientwood
Created March 4, 2021 11:33
Show Gist options
  • Save Ancientwood/1fdc3fc396595fc7899d997856641f96 to your computer and use it in GitHub Desktop.
Save Ancientwood/1fdc3fc396595fc7899d997856641f96 to your computer and use it in GitHub Desktop.
//自我数 (Self number)
//不能由任何一个整数加上这个整数的各位数字和生成的数,称之为自我数。例如:21不是自我数,因为21可以由整数15和15的各位数字1,5生成,即21=15+1+5。
function selfNumber(num){
for(let i=0;i<=1000;i++){
if(calc(i) == num)
return false;
}
return true;
}
function calc(num){
return parseInt(num/10) + num%10 + num;
}
selfNumber(10);
//Write a method to replace all spaces in a string with %20.
function replaceSpace(str){
let res = "";
for(let i=0;i<str.length;i++){
if(str.charAt(i) == " ")
res += "%20";
else
res += str.charAt(i);
}
return res;
//return str.replace(/ +/g,"%20");
}
//手动实现替换函数
function replaceFun(str,target,replacement){
let res = "";
for(let i=0;i<str.length;){
if(isMatch(str,i,target)){
i+=replacement.length;
res +=replacement;
}else {
res+=str[i];
i++;
}
}
return res;
}
function isMatch(str,pos,target){
for(let i=0;i<target.length && i+pos < str.length;i++){
if(str.charAt(pos+i) != target.charAt(i)){
return false;
}
}
return true;
}
replaceFun("123 455556 789","5","0")
/**
* Big Num
* @param {string} num1
* @param {string} num2
* @return {string}
*/
let multiply = function(num1, num2) {
//判断输入是不是数字
if(isNaN(num1) || isNaN(num2)) return ''
let len1 = num1.length,
len2 = num2.length
let res = []
//这里倒过来遍历很妙,不需要处理进位了
for (let i = len1 - 1; i >= 0; i--) {
for (let j = len2 - 1; j >= 0; j--) {
let index1 = i + j,
index2 = i + j + 1
let mul = num1[i] * num2[j] + (res[index2] || 0)
res[index2] = mul % 10
res[index1] = (res[index1] || 0) + Math.floor(mul / 10)
}
}
//去掉前置0
let result = res.join('').replace(/^0+/,'')
//不要转成数字判断,否则可能会超精度!
return !result ? '0' : result
}
multiply("123","45")
//单词去重
function cleanWords(str){
let arr = str.split(" "),
res = [arr[0]];
for(let i=0;i<arr.length;i++){
if(res.includes(arr[i])){
continue;
}
else{
res.push(arr[i]);
}
}
return res.join(" ");
}
cleanWords("Joins two or the more arrays, two and arrays returns returns a copy of the joined arrays");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment