Back home

ARTES #034

ARTES #034

ARTES 034

Algoritmo

292. Juego Nim

Dificultad: Fácil

Estás jugando el siguiente juego de Nim con tu amigo: Hay un montón de piedras sobre la mesa, cada vez uno de ustedes se turna para quitar de 1 a 3 piedras. El que retire la última piedra será el ganador. Tomarás el primer turno para retirar las piedras.

Ambos sois muy inteligentes y tenéis estrategias óptimas para el juego. Escribe una función para determinar si puedes ganar el juego dada la cantidad de piedras en el montón.

Ejemplo:

Input: 4
Output: false 
Explanation: If there are 4 stones in the heap, then you will never win the game;
             No matter 1, 2, or 3 stones you remove, the last stone will always be 
             removed by your friend.
Solución

这个是想出来了就简单

Idioma: Rápido

class Solution {
    func canWinNim(_ n: Int) -> Bool {
        
        return (n % 4 != 0)
    }
}

8. Cadena a entero (atoi)

Dificultad: Media

Implemente <span style="display: inline;">atoi</span>, que convierte una cadena en un número entero.

La función primero descarta tantos espacios en blanco como sea necesario hasta que se encuentre el primer carácter que no sea un espacio en blanco. Luego, a partir de este carácter, toma un signo más o menos inicial opcional seguido de tantos dígitos numéricos como sea posible y los interpreta como un valor numérico.

La cadena puede contener caracteres adicionales después de los que forman el número entero, que se ignoran y no tienen ningún efecto sobre el comportamiento de esta función.

Si la primera secuencia de caracteres que no son espacios en blanco en str no es un número entero válido, o si no existe dicha secuencia porque str está vacía o contiene solo caracteres de espacios en blanco, no se realiza ninguna conversión.

Si no se pudo realizar una conversión válida, se devuelve un valor cero.

Nota:

  • Sólo el carácter de espacio ' ' se considera carácter de espacio en blanco.
  • Supongamos que estamos tratando con un entorno que solo puede almacenar números enteros dentro del rango de enteros con signo de 32 bits: [−2<sup>31</sup>,  2<sup>31 </sup>− 1]. Si el valor numérico está fuera del rango de valores representables, se devuelve INT_MAX (2<sup>31 </sup>− 1) o INT_MIN (−2<sup>31</sup>).

Ejemplo 1:

Input: "42"
Output: 42

Ejemplo 2:

Input: "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
             Then take as many numerical digits as possible, which gets 42.

Ejemplo 3:

Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

Ejemplo 4:

Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical 
             digit or a +/- sign. Therefore no valid conversion could be performed.

Ejemplo 5:

Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
             Thefore INT_MIN (−231) is returned.
Solución

中规中矩的解法

Idioma: Rápido


class Solution {
    func myAtoi(_ str: String) -> Int {
        var newStr = str
        for cha in  newStr {//去除空格
            if cha == " " {
                newStr.remove(at:str.startIndex)
            }
            else{
                break;
            }
        }
        
        if newStr.count == 0 {
            return 0;
        }
        
        var sign = 1
        let first = newStr[newStr.startIndex]
        if first == "+" {
            sign = 1
            newStr.remove(at:str.startIndex)
        }
        else if (first == "-"){
            sign = -1;
            newStr.remove(at:str.startIndex)
        }
           
        var result = 0
        var temp = 0
        
        for cha in  newStr {
            if cha < "0" || cha > "9" {
                return result
            }
            
            
            temp = temp * 10 + (Int(String(cha)) ?? 0)
            
            
            result = temp * sign
            if result  > Int(Int32.max)  {
                return Int(Int32.max)
            }
            else if result < Int(Int32.min) {
                return Int(Int32.min)
            }
        }
        
        return result
    }
}

Revisión

这篇文章讲的是Adaptador 适配器设计模式:

https://dandan2009.github.io/2019/10/30/design-patterns-by-tutorials-the-power-of-OOP-part-3/

Consejos

我们第一次安装CocoaPods后,执行pod install,会克隆 https://github.com/CocoaPods/Specs master分支到~/.cocoapods/repos目录下,但是由于国内环境问题导致 git clone https://github.com/CocoaPods/Specs está disponible para su uso.

解决办法:

可以尝试下这个git clone https://git.coding.net/CocoaPods/Specs.git,https://gitclub.cn/CocoaPods/Specs

然后把Specs目录改名为master即可。~/.cocoapods/repos的目录层级如下: 15731384080733

https://git.coding.net/CocoaPods/Specs.git和 https://gitclub.cn/CocoaPods/Specs都是国内镜像,要快很多,还可以直接下载zip包,然后解压到~/.cocoapods/repos目录即可。

Compartir

昨天看到一个小伙子因为停车费,堵住了一个停车场大门,事情的起因是,小伙子是早上8点进入的停车场,下午2点离场,停车场的收费标准是停车不足12小时收费5元,但是收费员确要10元,收费员是两个50多岁的老头,我之前也遇到过,停车明明不足12小时却收10元,进场有门禁和摄像;估计很多人也遇到过,但是由于赶时间等原因,很多人不想为了5块钱和他们争吵,但是这次他们却遇到了个较真的;小伙子堵停车场门确实不对,但是小伙子较真的做法还是值得肯定的,生活中要多有这样的人,我们的生活或许会更美好; 在日常生活中我们很多人其实都会遇到类似的这样的事,但是因为我们觉得怕麻烦或得不偿失,而不去维护自己的合法权益,允许一些人践踏规则。比如这次事件对小伙子来说为了5元钱,却浪费了近3个小时,从这个角度讲确实不值,但是如果我们每个人与到这样的事都能站出来较真一下,维护规则,那么我们的生活会少很多藏污纳垢的地方.