I tried LeetCode every day 9. Palindrome Number (Python, Go)

Introduction

@Ishishow is running a free English word site E-tan.

I would like to work on letcode every day to improve my ability as a programmer and give my own way of solving it.

What is Leetcode

leetcode.com This is the practice of coding interviews for software developers. A total of more than 1,500 coding questions have been posted, and it seems that the same questions are often asked in actual interviews.

Introduction to Go language + algorithm I will solve it with Golang and Python to strengthen my brain. (Python is weak but experienced)

Third question (problem 09)

Palindrome Number

--Problem content (Japanese translation)

Determine if the integer is a palindrome. An integer is a palindrome if it is read in the same way forward and backward.

** Follow-up: ** Can I resolve without converting an integer to a string?

Example 1:

  Input: x = 121
  Output: true

Example 2:

  Input: x = -121
  Output: false
  Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

  Input: x = 10
  Output: false
  Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Example 4:

  Input: x = -101
  Output: false

Way of thinking

  1. Make a positive / negative judgment and process only positive.
  2. Make a character string and judge in reverse order

Explanation

  1. If it is negative, it will not be a palindrome.
  2. You can make an int str using the str function. Then use slices in reverse order. .. .. (Not recommended due to problem)

--Answer code

  class Solution(object):
      def isPalindrome(self, x):
          return str(x) == str(x)[::-1]

Judgment is made by reversing the character strings using slices! We received advice from @shiracamus. Since the value of the comparison expression is a boolean value, the conditional expression can be omitted. Previous code ↓

 def isPalindrome(self, x):
      if x >= 0:
          if str(x) == str(x)[::-1]:
              return True
      return False

--I'll write it in Go too!

  import "strconv"
  func isPalindrome(x int) bool {
  	s := strconv.Itoa(x)
  	r := []rune(s)
  	for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
  		if r[i] != r[j] {
  			return false
  		}
  	}
  	return true
  }

The solution is the same, but in the case of Go, the string is immutable, so this is the way to write it.

I also imported the strconv package and used Itoa. Integer To a.

Go and Python execution time

From the left, RunTime, Memory, language. キャプチャ.PNG

Another solution

I solved it as a number using the mechanism of 9.Reverse Integer that I solved the day before. (This is recommended.)

func isPalindrome(x int) bool {
    if x<0{
        return false
    }
    new_var := x 
    rev := 0
    for x!=0{
        pop := x%10
        x = x/10
        
        rev = rev *10 + pop
    }
    if rev==new_var{
        return true
    }else{
        return false
    }
}

--Self memo (Go)

Use the rune type to handle strings character by character

String can be cast to [] rune and [] byte.

The actual state of rune is int32, and unicode Large enough to represent 4 bytes

string and rune Arrays can be converted to each other, so if you want to cut a string

  package main
  
  import "fmt"
  
  func main() {
      nihongo := "Japanese"
  
      fmt.Printf("nihongo = %s\n", nihongo)
      fmt.Printf("nippon = %s\n", string([]rune(nihongo)[:2]))
  }

Like string [] runestring You can safely process it by converting it to .

Execution result

  nihongo =Japanese
  nippon =Japan

Referenced articles

First Go Language (on Windows) Part 4

Unicode knowledge to understand Go rune

Recommended Posts

I tried LeetCode every day 9. Palindrome Number (Python, Go)
I tried LeetCode every day 136. Single Number (Python, Go)
I tried LeetCode every day 125. Valid Palindrome (Python, Go)
I tried LeetCode every day 7. Reverse Integer (Python, Go)
I tried LeetCode every day 112. Path Sum (Python, Go)
I tried LeetCode every day 20. Valid Parentheses (Python, Go)
I tried LeetCode every day 118. Pascal's Triangle (Python, Go)
I tried LeetCode every day 1. Two Sum (Python, Go)
I tried LeetCode every day 141. Linked List Cycle (Python, Go)
I tried LeetCode every day 13. Roman to Integer (Python, Go)
I tried LeetCode every day 110. Balanced Binary Tree (Python, Go)
I tried LeetCode every day 14.Longest Common Prefix (Python, Go)
I tried LeetCode every day 119. Pascal's Triangle II (Python, Go)
I tried LeetCode every day 21. Merge Two Sorted Lists (Python, Go)
I tried LeetCode every day 168. Excel Sheet Column Title (Python, Go)
I tried LeetCode every day 111. Minimum Depth of Binary Tree (Python, Go)
I tried LeetCode every day 26. Remove Duplicates from Sorted Array (Python, Go)
I tried LeetCode every day 160. Intersection of Two Linked Lists (Python, Go)
I tried LeetCode every day 121 Best Time to Buy and Sell Stock (Python, Go)
I tried LeetCode every day 108. Convert Sorted Array to Binary Search Tree (Python, Go)
I tried LeetCode every day 167. Two Sum II --Input array is sorted (Python, Go)
I tried Grumpy (Go running Python).
I tried running faiss with python, Go, Rust
I tried Python> autopep8
I tried Python> decorator
I tried to solve AOJ's number theory with Python
I tried fp-growth with python
I tried scraping with Python
[Python] I tried using OpenPose
I tried gRPC with Python
I tried scraping with python
I tried to touch Python (installation)
I tried web scraping with python.
I tried using Thonny (Python / IDE)
I tried running prolog with python 3.8.2.
I tried Line notification in Python
I tried SMTP communication with Python
[Python] I tried using YOLO v3
Mayungo's Python Learning Episode 6: I tried to convert a character string to a number
(Python) I tried to analyze 1 million hands ~ I tried to estimate the number of AA ~
I tried to discriminate a 6-digit number with a number discrimination application made with python
I tried to summarize Python exception handling
I tried to implement PLSA in Python
I tried to implement permutation in Python
Wrangle x Python book I tried it [2]
I tried scraping Yahoo News with Python
Python3 standard input I tried to summarize
I tried sending an email with python.
I tried using Bayesian Optimization in Python
I tried using UnityCloudBuild API from Python
I tried to implement ADALINE in Python
I tried a functional language with Python
I tried recursion with Python ② (Fibonacci sequence)
I tried to implement PPO in Python
Python: I tried the traveling salesman problem
Wrangle x Python book I tried it [1]
Mayungo's Python Learning Episode 8: I tried input
[Python] I tried to calculate TF-IDF steadily
I tried to touch Python (basic syntax)
I tried the Python Tornado Testing Framework
#I tried something like Vlookup with Python # 2