首页 > 其他分享 >leetcode 504. Base 7

leetcode 504. Base 7

时间:2023-05-30 17:35:31浏览次数:45  
标签:num neg self Base str ans return 504 leetcode

Given an integer, return its base 7 string representation.

Example 1:

Input: 100
Output: "202"

Example 2:

Input: -7
Output: "-10"

Note: The input will be in range of [-1e7, 1e7].

class Solution(object):
    def convertToBase7(self, num):
        """
        :type num: int
        :rtype: str
        """
        """
        Input: 100
Output: "202"
100%7=14,2
14%7=2,0
2%7=2,xxx
        """
        is_neg = False
        if num < 0:            
            num = -num
            is_neg = True
        ans = ""
        while num >= 7:
            ans = str(num%7) + ans
            num = num/7
        ans = str(num) + ans
        return ans if not is_neg else "-"+ans

 

or

class Solution(object):
    def convertToBase7(self, num):
        """
        :type num: int
        :rtype: str
        """
        """
        Input: 100
Output: "202"
100%7=14,2
14%7=2,0
2%7=2,xxx
        """
        if num == 0:
            return '0'
        is_neg = False
        if num < 0:            
            num = -num
            is_neg = True        
        ans = ""
        while num != 0:
            ans = str(num%7) + ans
            num = num/7        
        return ans if not is_neg else "-"+ans

使用递归:

class Solution(object):
    def convertToBase7(self, num):
        """
        :type num: int
        :rtype: str
        """
        if num < 0:
            return "-"+self.convertToBase7(-num)
        if num < 7:
            return str(num)
        return self.convertToBase7(num/7) + str(num%7)

 

标签:num,neg,self,Base,str,ans,return,504,leetcode
From: https://blog.51cto.com/u_11908275/6381004

相关文章

  • leetcode 350. Intersection of Two Arrays II
    Giventwoarrays,writeafunctiontocomputetheirintersection.Example:Givennums1=[1,2,2,1],nums2=[2,2],return[2,2].Note:Eachelementintheresultshouldappearasmanytimesasitshowsinbotharrays.Theresultcanbeinanyorder.Foll......
  • leetcode 83. Remove Duplicates from Sorted List
    Givenasortedlinkedlist,deleteallduplicatessuchthateachelementappearonlyonce.Forexample,Given1->1->2,return1->2.Given1->1->2->3->3,return1->2->3.#Definitionforsingly-linkedlist.#classListNode(object)......
  • leetcode 53. Maximum Subarray
    Givenanintegerarraynums,findthecontiguoussubarray (containingatleastonenumber)whichhasthelargestsumandreturnitssum.Example:Input:[-2,1,-3,4,-1,2,1,-5,4],Output:6Explanation: [4,-1,2,1]hasthelargestsum=6.Followup:Ifyouhavef......
  • leetcode 101. Symmetric Tree
    Givenabinarytree,checkwhetheritisamirrorofitself(ie,symmetricarounditscenter).Forexample,thisbinarytree[1,2,2,3,4,4,3]issymmetric:1/\22/\/\3443Butthefollowing[1,2,2,null,3,null,3]isnot:1/\2......
  • leetcode 191. Number of 1 Bits
    Writeafunctionthattakesanunsignedintegerandreturnsthenumberof’1'bitsithas(alsoknownastheHammingweight).Forexample,the32-bitinteger’11'hasbinaryrepresentation00000000000000000000000000001011,sothefunctionshould......
  • leetcode 326. Power of Three
    Givenaninteger,writeafunctiontodetermineifitisapowerofthree.Followup:Couldyoudoitwithoutusinganyloop/recursion?classSolution(object):defisPowerOfThree(self,n):""":typen:int......
  • leetcode 231. Power of Two
    Givenaninteger,writeafunctiontodetermineifitisapoweroftwo.classSolution(object):defisPowerOfTwo(self,n):""":typen:int:rtype:bool"""#-4???ifn>......
  • leetcode 27. Remove Element
    Givenanarraynumsandavalueval,removeallinstancesofthatvaluein-placeandreturnthenewlength.Donotallocateextraspaceforanotherarray,youmustdothisbymodifyingtheinputarrayin-placeTheorderofelementscanbechanged.Itdoesn&......
  • leetcode 594. Longest Harmonious Subsequence
    Wedefineaharmoniousarrayisanarraywherethedifferencebetweenitsmaximumvalueanditsminimumvalueisexactly1.Now,givenanintegerarray,youneedtofindthelengthofitslongestharmonioussubsequenceamongallitspossiblesubsequences.E......
  • leetcode 836. Rectangle Overlap
    Arectangleis representedasa list[x1,y1,x2,y2],where (x1,y1) arethecoordinatesofitsbottom-leftcorner,and(x2, y2) arethecoordinatesofitstop-rightcorner.Tworectanglesoverlapiftheareaoftheirintersectionispositive. Tobecl......