LeetCode 1-10(JavaScript)

我要开始刷算法了。缓慢刷题中。


6. Z 字形变换

难度:中等
对我来说:困难
在这个题让我深刻的意识到我是笨比。明明字符串拼串很简单,我愣是撞南墙不回头,冲着二维数组使劲去了。

将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 “LEETCODEISHIRING” 行数为 3 时,排列如下:

之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“LCIRETOESIIGEDHN”。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);

示例 1:

输入: s = “LEETCODEISHIRING”, numRows = 3
输出: LCIRETOESIIGEDHN

示例 2:

输入: s = “LEETCODEISHIRING”, numRows = 4
输出: LDREOEIIECIHNTSG
解释:
在这里插入图片描述
输入: s = “LEETCODEISHIRING”, numRows = 4
输出: LDREOEIIECIHNTSG

示例 3:

输入: s =“Apalindromeisaword,phrase,number,orothersequenceofunitsthatcanbereadthesamewayineitherdirection,withgeneralallowancesforadjustmentstopunctuationandworddividers.”, numRows = 2
输出:Aore,sohraerwraancaiprmods,roreeftaeesmniie,ieawnrdetntnndv.adew,anereqcustbaeeitdcntnlocojmsuuoddislniaprubohunntcndhwyhrtohealefuttpaiwrdrishmteiataeiglssotoe

示例 4:

扫描二维码关注公众号,回复: 10455294 查看本文章

输入: s =“A”, numRows = 1
输出:A

var convert = function(s, numRows) {
	let a = []
	let index = 0
	let down = true //index 是否下移
	if (numRows === 1) {
		return s
	}
	for (let i = 0; i < s.length; i++) {
		// a[index]是否为undefined
		a[index] = a[index] ? a[index] + s[i] : s[i]
		index = down ? ++index : --index
		if (index === 0) {
			down = true
		} else if (index === numRows - 1) {
			down = false
		}
	}
	return a.join('')
}

7. 整数反转

难度:简单
对我来说:简单

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

示例 1:

输入: 123
输出: 321

示例 2:

输入: -123
输出: -321

示例 3:

输入: 120
输出: 21

注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。

var reverse = function(x) {
    let str
	if (x < 0) {
	    str = (-x).toString()
	} else {
		str = x.toString()
	}
	str = str.split('').reverse().join('')
	if(str.length>10 || str.length === 10 && str > (x<0?"2147483648":"2147483647")){
		return 0 
	}
			
	if(x<0){
		x = -str
	}else{
		x = +str
	}
	return x
};
发布了131 篇原创文章 · 获赞 451 · 访问量 54万+

猜你喜欢

转载自blog.csdn.net/qq_36667170/article/details/105280403