add new solutions

This commit is contained in:
Yiyang Kang 2026-02-17 14:25:55 +09:00
parent 489fa73880
commit 0f5f9e331c
Signed by: kkyy
SSH key fingerprint: SHA256:lJSbAzC3MvrSORdvIVK6h/3g+rVKJNzM7zq0MgA9WKY
11 changed files with 539 additions and 0 deletions

View file

@ -0,0 +1,49 @@
package q43
import "slices"
func multiply(num1, num2 string) string {
if num1 == "0" || num2 == "0" {
return "0"
}
l1, l2 := len(num1), len(num2)
res := make([]byte, l1+l2)
// Calculation
for i1 := range l1 {
n1 := num1[l1-1-i1] - '0'
if n1 == 0 {
continue
}
for i2 := range l2 {
n2 := num2[l2-1-i2] - '0'
j := i1 + i2
res[j] += n1 * n2
if res[j] > 9 {
res[j+1] += res[j] / 10
res[j] = res[j] % 10
}
}
for i := l2 + i1; res[i] > 9; i++ {
res[i+1] += res[i] / 10
res[i] = res[i] % 10
}
}
// Post process
for i := len(res) - 1; i >= 0; i-- {
if res[i] > 0 {
res = res[:i+1]
break
}
}
slices.Reverse(res)
for i := range res {
res[i] = res[i] + '0'
}
return string(res)
}
var _ = multiply

View file

@ -0,0 +1,63 @@
package q68
var (
emptyLine = make([]byte, 100)
buf = make([]byte, 100)
)
func init() {
for i := range emptyLine {
emptyLine[i] = ' '
}
}
func emitLine(line []byte, words []string, justifyLeft bool) string {
spaces := len(line)
for i := range words {
spaces -= len(words[i])
}
lenSep := spaces / max(len(words)-1, 1)
leftover := spaces % max(len(words)-1, 1)
offset := len(words[0])
copy(line, words[0])
for i := 1; i < len(words); i++ {
var spaces = 1
if !justifyLeft {
spaces = lenSep
if i <= leftover {
spaces++
}
}
offset += spaces
copy(line[offset:], words[i])
offset += len(words[i])
}
return string(line)
}
func fullJustify(words []string, maxWidth int) []string {
ret := []string{}
line := buf[:maxWidth]
copy(line, emptyLine)
i := 0
lineLen := len(words[0])
for j := 1; j < len(words); j++ {
if lineLen+1+len(words[j]) <= maxWidth {
lineLen += 1 + len(words[j])
continue
}
ret = append(ret, emitLine(line, words[i:j], false))
copy(line, emptyLine)
i = j
lineLen = len(words[j])
}
// Last line
return append(ret, emitLine(line, words[i:], true))
}
var _ = fullJustify

View file

@ -0,0 +1,56 @@
package q8
const (
MIN = -(1 << 31)
MAX = 1<<31 - 1
)
func myAtoi(s string) int {
sign := 0
num := 0
Loop:
for i := range len(s) {
c := s[i]
switch c {
case '-':
if sign != 0 {
break Loop
}
sign = -1
case '+':
if sign != 0 {
break Loop
}
sign = 1
case ' ':
if sign != 0 {
break Loop
}
default:
if c < '0' || c > '9' {
break Loop
}
if sign == 0 {
sign = 1
}
num = num*10 + int(c-'0')
if sign*num < MIN {
num = -MIN
break Loop
}
if sign*num > MAX {
num = MAX
break Loop
}
}
}
return sign * num
}
var _ = myAtoi