日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > c/c++ >内容正文

c/c++

剑指offer(刷题1-10)--c++,Python版本

發(fā)布時(shí)間:2023/12/13 c/c++ 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 剑指offer(刷题1-10)--c++,Python版本 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

文章目錄

  • 目錄
    • 第一題:
      • 解題思路:
      • 代碼實(shí)現(xiàn):
        • c++
          • 順序查找
          • 二分查找
        • Python
    • 第二題:
      • 解題思路:
      • 代碼實(shí)現(xiàn):
        • c++
        • python
    • 第三題:
      • 解題思路:
      • 代碼實(shí)現(xiàn):
        • c++
          • 使用棧輔助
          • 反轉(zhuǎn)鏈表
        • python
    • 第四題:
      • 解題思路:
      • 代碼實(shí)現(xiàn):
        • c++
        • python
    • 第五題:
      • 解題思路:
      • 代碼實(shí)現(xiàn):
        • c++
        • python
    • 第六題:
      • 解題思路:
      • 代碼實(shí)現(xiàn):
        • c++
        • python
    • 第七題:
      • 解題思路:
      • 代碼實(shí)現(xiàn):
        • c++
          • 第一種:
          • 第二種:
        • python
    • 第八題:
      • 解題思路:
      • 代碼實(shí)現(xiàn):
        • c++
          • 遞歸的方法(該方法的通過(guò)率比較低):
          • 歸納法(100%通過(guò)):
          • 動(dòng)態(tài)規(guī)劃的方法(100%通過(guò))
        • python
    • 第九題:
      • 解題思路:
      • 代碼實(shí)現(xiàn):
          • 遞歸方法
        • c++
          • 非遞歸方法:
        • python
    • 第十題:
      • 解題思路:
      • 代碼實(shí)現(xiàn):
        • c++
        • python

目錄

第一題:

在一個(gè)二維數(shù)組中(每個(gè)一維數(shù)組的長(zhǎng)度相同),每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請(qǐng)完成一個(gè)函數(shù),輸入這樣的一個(gè)二維數(shù)組和一個(gè)整數(shù),判斷數(shù)組中是否含有該整數(shù)。

解題思路:

這是一個(gè)查找問(wèn)題,由于題目特定強(qiáng)調(diào)了有序的數(shù)組,所以我們?nèi)绻褂弥苯邮褂庙樞虿檎铱隙ㄊ遣划?dāng)?shù)摹K晕覀兛梢岳脭?shù)組的性質(zhì)進(jìn)行查找。

  • 1.使用順序查找,但是不從第一個(gè)數(shù)開(kāi)始找,而是從二位數(shù)組的左上角的數(shù)開(kāi)始找,如果正好相等,則返回,如果小于被查找的數(shù),則行號(hào)加一,否則,列號(hào)減一。
  • 2.使用二分查找??梢员闅v行或者列,先比較該行或者該列的最后一個(gè)元素與要查找的元素的大小關(guān)系,然后針對(duì)該行或者列進(jìn)行二分查找

代碼實(shí)現(xiàn):

c++

順序查找
#include <iostream> #include <vector>using namespace std;//二維數(shù)組查找 bool Find(int target , vector<vector<int>> array){if(array.empty()){return false;}int row = array.size();int col = array[0].size();int i=0 , j = col - 1;while(i < row && j >= 0){if(target == array[i][j]){return true;}else if (target > array[i][j]){i ++;}else{j --;}}return false; }int main(){int a1[] = { 1, 1, 8, 9, };int a2[] = { 2, 4, 9, 12, };int a3[] = { 4, 7, 10, 13, };int a4[] = { 6, 8, 11, 15, };vector<vector<int>> myArry;myArry.push_back(vector<int>(a1, a1 + 4));myArry.push_back(vector<int>(a2, a2 + 4));myArry.push_back(vector<int>(a3, a3 + 4));myArry.push_back(vector<int>(a4, a4 + 4));cout<<"the result is : "<<Find(100,myArry)<<endl;return 0; }
二分查找
#include <iostream> #include <vector> #include <algorithm>using namespace std;//二維數(shù)組查找 bool Find(int target , vector<vector<int>> array){if(array.empty()){return false;}int row = array.size(); //行的數(shù)目//每行進(jìn)行查找for(int i = 0;i<row;i++){if(binary_search(array[i].begin(),array[i].end(),target)){return true;}}//掃描完每行后沒(méi)有發(fā)現(xiàn),則說(shuō)明沒(méi)有找到return false; }int main(){int a1[] = { 1, 1, 8, 9, };int a2[] = { 2, 4, 9, 12, };int a3[] = { 4, 7, 10, 13, };int a4[] = { 6, 8, 11, 15, };vector<vector<int>> myArry;myArry.push_back(vector<int>(a1, a1 + 4));myArry.push_back(vector<int>(a2, a2 + 4));myArry.push_back(vector<int>(a3, a3 + 4));myArry.push_back(vector<int>(a4, a4 + 4));cout<<"the result is : "<<Find(4,myArry)<<endl;return 0; }

Python

def Find(target ,array):if array == []:return Falserow = len(array) - 1col = len(array[0])i = 0 j = col - 1while i < row and j >= 0:if target == array[i][j]:return Trueelif target > array[i][j]:i += 1else:j -= 1return FalseFind(1,[[1, 1, 8, 9],[2, 4, 9, 12],[4, 7, 10, 13],[6, 8, 11, 15]])

第二題:

請(qǐng)實(shí)現(xiàn)一個(gè)函數(shù),將一個(gè)字符串中的每個(gè)空格替換成“%20”。例如,當(dāng)字符串為We Are Happy.則經(jīng)過(guò)替換之后的字符串為We%20Are%20Happy。

解題思路:

  • 一般的思維:遍歷字符串,然后找到每個(gè)字符串中每個(gè)空格的位置,然后使用“%20”進(jìn)行替換;但是由于字符串存儲(chǔ)的是順序結(jié)構(gòu),所以插入字符串會(huì)導(dǎo)致字符串中字符后移;所以可以先統(tǒng)計(jì)出字符串中空字符的個(gè)數(shù),然后首先算出要移動(dòng)的位置,從字符串后面往前逐步替換掉。
  • 借助c++中的string類(lèi)的方法,首選將字符串轉(zhuǎn)換為string ,然后調(diào)用find函數(shù)和replace函數(shù)將每個(gè)空格替換成“%20”,最后將string轉(zhuǎn)換為c_string.

代碼實(shí)現(xiàn):

c++

#include <string>class Solution { public:void replaceSpace(char *str,int length) {string tempStr(str); //將c風(fēng)格的字符串轉(zhuǎn)換為string//遍歷字符串,找到每個(gè)空格的位置,然后替換掉它for(int i=0 ; i <tempStr.size(); i++){int tempIndex = tempStr.find(" " , i); //前面搜過(guò)的一定不能重復(fù)搜索if(tempIndex!=-1){tempStr.replace(tempIndex,1,"%20");}}strcpy(str,tempStr.c_str());}};

python

## 字符串空格替換 def replaceSpace(s):s = s.replace(" ","%20")return s replaceSpace("We Are Happy")

第三題:

輸入一個(gè)鏈表,按鏈表值從尾到頭的順序返回一個(gè)ArrayList。

解題思路:

  • 借助于棧結(jié)構(gòu),保存數(shù)據(jù)然后依次出棧即可;時(shí)間復(fù)雜度為O(N),空間復(fù)雜度為O(N);
  • 借助vector數(shù)組反轉(zhuǎn)函數(shù),先用vector保存順序遍歷鏈表的值,然后直接對(duì)數(shù)組進(jìn)行反轉(zhuǎn),然后輸出;時(shí)間復(fù)雜度為O(N),空間復(fù)雜度為O(1);
  • 先將鏈表反轉(zhuǎn),然后再依次遍歷。

代碼實(shí)現(xiàn):

c++

使用棧輔助
#include <functional> #include <string> #include <cstring> #include <stack>using namespace std;struct ListNode {int val;struct ListNode *next;ListNode(int x) :val(x), next(NULL) {}};vector<int> printListFromTailToHead(ListNode *head){stack<int> dataStack;vector<int> arrayList;if(head == NULL){return ;}while(head != NULL){dataStack.push(head->val);head = head->next;}while(!dataStack.empty()){arrayList.push_back(dataStack.top());dataStack.pop();}return arrayList; }
反轉(zhuǎn)鏈表
#include <iostream> #include <vector> #include <algorithm> #include <functional>using namespace std;struct ListNode {int val;struct ListNode *next;ListNode(int x) :val(x), next(NULL) {}};vector<int> printListFromTailToHead(ListNode *head){ListNode *pCur , *pPre , *pNext;pPre = head;pCur = pPre->next;while(pCur){pNext = pCur->next;pCur->next = pPre;pPre = pCur;pCur = pNext;}head->next = NULL;head = pPre;vector<int> arrayList;while(head){arrayList.push_back(head->val);head = head->next;}return arrayList; }

python

## 鏈表反轉(zhuǎn)輸出 def printListFromTailToHead(listNode):tempList = []#順序訪問(wèn)鏈表,并將鏈表的值保存while listNode != None:tempList.append(listNode.val)listNode = listNode.nextreturn list(reversed(tempList)) #直接輸出列表的反轉(zhuǎn)

第四題:

輸入某二叉樹(shù)的前序遍歷和中序遍歷的結(jié)果,請(qǐng)重建出該二叉樹(shù)。假設(shè)輸入的前序遍歷和中序遍歷的結(jié)果中都不含重復(fù)的數(shù)字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹(shù)并返回。

解題思路:

  • 由于是二叉樹(shù)的構(gòu)建,所以我們應(yīng)該想到用遞歸的方法進(jìn)行構(gòu)建,遞歸的終止條件就是前序遍歷和中序遍歷的節(jié)點(diǎn)個(gè)數(shù)為1,;遞歸的過(guò)程主要是從pre中把根節(jié)點(diǎn)確定,然后再?gòu)腣in中根據(jù)確定的根節(jié)點(diǎn)確定該節(jié)點(diǎn)的左右子樹(shù)集合。

代碼實(shí)現(xiàn):

c++

#include <iostream> #include <vector> #include <algorithm> #include <functional>using namespace std;//二叉樹(shù)節(jié)點(diǎn)結(jié)構(gòu)定義 struct TreeNode {int val; //值域TreeNode *left;TreeNode *right;TreeNode(int x) : val(x), left(NULL), right(NULL) {}}; //二叉樹(shù)重建 class Solution { public:TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {if(pre.size() != vin.size()){return NULL;}int vinLen = vin.size();if(vinLen == 0){return NULL;}vector<int> left_pre , left_vin , right_pre , right_vin;TreeNode * head = new TreeNode(pre[0]);int headIndex = 0;for(int i=0 ; i < vin.size() ; i++ ){if(vin[i] == pre[0]){headIndex = i;break;}}for(int i = 0; i < headIndex ; i++){left_vin.push_back(vin[i]);left_pre.push_back(pre[i+1]);//前序第一個(gè)為根節(jié)點(diǎn)}for(int i = headIndex + 1 ; i < vin.size() ; i++){right_pre.push_back(pre[i]);right_vin.push_back(vin[i]);}//和shell排序的思想類(lèi)似,取出前序和中序遍歷根節(jié)點(diǎn)左邊和右邊的子樹(shù)//遞歸,再對(duì)其進(jìn)行上述所有步驟,即再區(qū)分子樹(shù)的左、右子子數(shù),直到葉節(jié)點(diǎn)head->left = reConstructBinaryTree(left_pre,left_vin);head->right = reConstructBinaryTree(right_pre,right_vin);return head;}};

python

##重建二叉樹(shù)#樹(shù)的節(jié)點(diǎn)結(jié)構(gòu) class TreeNode:def __init__(self, x):self.val = xself.left = Noneself.right = None#重構(gòu)二叉樹(shù) def reConstructBinaryTree(pre , tin):if len(pre)!= len(tin):return NonerootNode = TreeNode(pre[0])rootTinIndex = tin.index(rootNode.val)if rootTinIndex == None:return NonerootNode.left = reConstructBinaryTree(pre[1:rootTinIndex + 1] , tin(:rootTinIndex))rootNode.right =reConstructBinaryTree(pre[rootTinIndex+1:] , tin(rootTinIndex:))return root

第五題:

用兩個(gè)棧來(lái)實(shí)現(xiàn)一個(gè)隊(duì)列,完成隊(duì)列的Push和Pop操作。 隊(duì)列中的元素為int類(lèi)型。

解題思路:

  • 使用兩個(gè)棧,一個(gè)用于實(shí)現(xiàn)隊(duì)頭,一個(gè)用于實(shí)現(xiàn)隊(duì)尾操作。需要注意的是出隊(duì)操作,如果用于實(shí)現(xiàn)隊(duì)頭的那個(gè)棧沒(méi)有數(shù)據(jù),則需要將實(shí)現(xiàn)隊(duì)尾棧中的數(shù)據(jù)復(fù)制到其中。

代碼實(shí)現(xiàn):

c++

#include <iostream> #include <vector> #include <algorithm> #include <functional> #include <stack>using namespace std;class solution{ private:stack<int> stack1; //隊(duì)頭stack<int> stack2; //隊(duì)尾 public:void push(int node){stack2.push(node);}int pop(){if(stack1.empty() && stack2.empty()){ //隊(duì)列為空return -1;}if(stack1.empty()){ //隊(duì)列一半為空while(!stack2.empty()){stack1.push(stack2.top());stack2.pop();}}int tempData = stack1.top();stack1.pop();return tempData;} };int main(){solution s;s.push(1);s.push(2);s.push(3);cout<<s.pop()<<endl;cout<<s.pop()<<endl;cout<<s.pop()<<endl;return 0; }

python

## 兩個(gè)棧實(shí)現(xiàn)隊(duì)列 class Solution:def __init__(self):self.stack1 = []self.stack2 = []def push(self, node):# write code hereself.stack1.append(node)def pop(self):# return xxif self.stack1 == [] and self.stack2 == []:return Noneif self.stack2 == []:while(len(self.stack1)):self.stack2.append(self.stack1.pop())return self.stack2.pop()if __name__ == "__main__":s = Solution()s.push(1)s.push(2)s.push(0)print s.pop()

第六題:

把一個(gè)數(shù)組最開(kāi)始的若干個(gè)元素搬到數(shù)組的末尾,我們稱(chēng)之為數(shù)組的旋轉(zhuǎn)。 輸入一個(gè)非減排序的數(shù)組的一個(gè)旋轉(zhuǎn),輸出旋轉(zhuǎn)數(shù)組的最小元素。 例如數(shù)組{3,4,5,1,2}為{1,2,3,4,5}的一個(gè)旋轉(zhuǎn),該數(shù)組的最小值為1。 NOTE:給出的所有元素都大于0,若數(shù)組大小為0,請(qǐng)返回0。

解題思路:

  • 首先肯定是可以通過(guò)STL中的算法,將旋轉(zhuǎn)后的數(shù)組進(jìn)行排序后,然后輸出第一個(gè)元素的值便可;
  • 可以利用旋轉(zhuǎn)素組的特性,是將一個(gè)有序的數(shù)組的前一部分搬到數(shù)組的末尾,所以數(shù)組可以分為2塊,前一塊和后一塊都是一種升序的數(shù)組,而轉(zhuǎn)折點(diǎn)就是最小值。

代碼實(shí)現(xiàn):

c++

class Solution { public:int minNumberInRotateArray(vector<int> rotateArray) {if(rotateArray.size() == 0){return 0;}for(int i = 0 ; i < rotateArray.size() ; i++ ){if(rotateArray[i] < rotateArray[0]){ //找到后面第一個(gè)比數(shù)組第一個(gè)元素小的元素return rotateArray[i]; }}return rotateArray[0]; //如果沒(méi)有找到,說(shuō)明最小的元素在數(shù)組的第一個(gè)位置} };

python

# -*- coding:utf-8 -*- class Solution:def minNumberInRotateArray(self, rotateArray):# write code hereif len(rotateArray) == 0:return 0for i in range(len(rotateArray)):if rotateArray[i] < rotateArray[0]:return rotateArray[i]return rotateArray[0]

第七題:

大家都知道斐波那契數(shù)列,現(xiàn)在要求輸入一個(gè)整數(shù)n,請(qǐng)你輸出斐波那契數(shù)列的第n項(xiàng)(從0開(kāi)始,第0項(xiàng)為0)。
n<=39

解題思路:

  • 使用for循環(huán)遍歷,使用斐波那契數(shù)列推到公式,得出每個(gè)數(shù),然后由一個(gè)數(shù)組進(jìn)行保存。
  • 由于不需要整個(gè)數(shù)列,只是數(shù)列的最后一項(xiàng)想,所以可以將存儲(chǔ)空間直接取3,每次求解迭代的時(shí)候更新進(jìn)行。

代碼實(shí)現(xiàn):

c++

第一種:
class Solution { public:int Fibonacci(int n) {vector<int> fibonacciArray(n+1);if(n<=0){return 0; }fibonacciArray[0] = 0;fibonacciArray[1] = 1;for(int i = 2 ; i < n+1 ; i++){fibonacciArray[i] = fibonacciArray[i-2] + fibonacciArray[i-1];}return fibonacciArray[n];} };
第二種:
class Solution { public:int Fibonacci(int n) {vector<int> fibonacciArray(3);if(n<=0){return 0; }if(n < 2){return 1;}fibonacciArray[0] = 0;fibonacciArray[1] = 1;for(int i = 2 ; i < n+1 ; i++){fibonacciArray[2] = fibonacciArray[0] + fibonacciArray[1];fibonacciArray[0] = fibonacciArray[1];fibonacciArray[1] = fibonacciArray[2];}return fibonacciArray[2];} };

python

#輸出斐波那契數(shù)列的第N項(xiàng) def Fibonacci(n):if n < 0 :return -1elif n==0:return 0elif n < 2:return 1else:pre = 0cur = 1for i in range(2,n+1):last = pre + curpre = curcur = lastreturn lastFibonacci(3)

第八題:

一只青蛙一次可以跳上1級(jí)臺(tái)階,也可以跳上2級(jí)。求該青蛙跳上一個(gè)n級(jí)的臺(tái)階總共有多少種跳法(先后次序不同算不同的結(jié)果)。

解題思路:

  • 歸納:
    把臺(tái)階都看成是木板,即有n塊木板,其中最后一塊木板是青蛙的目的地,是必須存在的,所以總共是n-1塊木板可以選擇。由于青蛙一次可以跳一級(jí)也可以一次跳兩級(jí),所以對(duì)于當(dāng)前這個(gè)木板,它可以被跳也可以不被跳,那么久總共存在2^(n-1)種可能。
  • 遞歸
    記跳 n 級(jí)臺(tái)階有 f(n) 種方法
    如果第一次跳 1 級(jí),那么之后的 n-1 級(jí)有 f(n-1) 種跳法
    如果第一次跳 2 級(jí),那么之后的 n-2 級(jí)有 f(n-2) 種跳法
    實(shí)際上就是首兩項(xiàng)為 1 和 2 的斐波那契數(shù)列

代碼實(shí)現(xiàn):

c++

遞歸的方法(該方法的通過(guò)率比較低):
#include <iostream> #include <vector> using namespace std; int jumpFloorII(int number) {if(number <=0){return -1;}else if(number == 1){return 1;}else if(number == 2){return 2;}else{return jumpFloorII(number - 1) + jumpFloorII(number - 2);}}int main(){cout<<jumpFloorII(5)<<endl;return 0; }
歸納法(100%通過(guò)):
#include <iostream> #include <vector> #include <cmath>using namespace std;int jumpFloorII(int number) {if(number <= 0){return -1;}else{return pow(2,number-1);}}int main(){cout<<jumpFloorII(6)<<endl;return 0; }
動(dòng)態(tài)規(guī)劃的方法(100%通過(guò))
class Solution { public:int jumpFloorII(int number) {vector<int> dp(number+1, 1); //創(chuàng)建動(dòng)態(tài)U規(guī)劃列表for (int i=2; i<=number; i++) for(int j=1; j<i; j++)dp[i] += dp[j];return dp[number];} };

python

##青蛙跳臺(tái)階問(wèn)題 #歸納方法 def jumpFloorII(number):if number <= 0:return -1else:return 2 ** (number - 1)jumpFloorII(5)

第九題:

我們可以用21的小矩形橫著或者豎著去覆蓋更大的矩形。請(qǐng)問(wèn)用n個(gè)21的小矩形無(wú)重疊地覆蓋一個(gè)2*n的大矩形,總共有多少種方法?

解題思路:

  • 遞歸:
    f(1) = 1;
    f(2) = 2;
    當(dāng)n>2時(shí),畫(huà)圖可知,第一塊小矩形可橫放和豎放。橫放后剩余的長(zhǎng)度為n-2,豎放后剩余的長(zhǎng)度為n-1。
    所以:f(n) = f(n-1) + f(n-2); (n > 2)
  • 類(lèi)比:
    我們對(duì)算法模型做些簡(jiǎn)化,我們知道,只可以放置兩種類(lèi)型的小矩形,一種是豎著放的21矩形,另一種是兩塊橫著放的21矩形上下放置形成的22正方形,而題目要放置的是2n的大矩形。
    我們將上面模型映射到一維,即是我們有一條長(zhǎng)度為n的線段,現(xiàn)在要么放置長(zhǎng)度為1,要么放置長(zhǎng)度為2的線段,請(qǐng)將該線段填滿(mǎn)。
    這讓我想起了走階梯的題目,一個(gè)n級(jí)階梯,每次要么走一級(jí)要么兩級(jí),請(qǐng)問(wèn)有多少種方法。
    綜上分析,可知,
    n = 1時(shí), f(n) = 1;
    n = 2時(shí), f(n) = 2;
    n > 2時(shí),f(n) = f(n - 1) + f(n - 2);

代碼實(shí)現(xiàn):

遞歸方法

c++

#include <iostream> #include <vector> #include <cmath>using namespace std;int rectCover(int number) {if(number < 0 ){return -1;}else if(number ==0){return 0;}else if(number == 1){return 1;}else if(number == 2){return 2;}else{return rectCover(number - 1) + rectCover(number - 2);}}int main(){cout<<rectCover(6)<<endl;return 0; }
非遞歸方法:
#include <iostream> #include <vector> #include <cmath>using namespace std;int rectCover(int number) {if(number < 0 ){return -1;}else if(number ==0){return 0;}else if(number == 1){return 1;}else if(number == 2){return 2;}vector<int> tempArry(3);tempArry[0] = 1;tempArry[1] = 2;for(int i = 3 ; i <= number;i++){tempArry[2] = tempArry[0] + tempArry[1];tempArry[0] = tempArry[1];tempArry[1] = tempArry[2];}return tempArry[2]; }int main(){cout<<rectCover(6)<<endl;return 0; }

python

#矩形覆蓋問(wèn)題 def rectCover(number):if number<0:return -1elif number==0:return 0elif number==1:return 1elif number == 2:return 2else:return rectCover(number -1) + rectCover(number - 2)rectCover(6)

第十題:

輸入一個(gè)整數(shù),輸出該數(shù)二進(jìn)制表示中1的個(gè)數(shù)。其中負(fù)數(shù)用補(bǔ)碼表示。

解題思路:

  • 通過(guò)移位操作,每次與1做與,求出其中1的個(gè)數(shù),一定要注意負(fù)數(shù)的情況
  • 比較巧的做法
    如果一個(gè)整數(shù)不為0,那么這個(gè)整數(shù)至少有一位是1。如果我們把這個(gè)整數(shù)減1,那么原來(lái)處在整數(shù)最右邊的1就會(huì)變?yōu)?,原來(lái)在1后面的所有的0都會(huì)變成1(如果最右邊的1后面還有0的話)。其余所有位將不會(huì)受到影響。
    舉個(gè)例子:一個(gè)二進(jìn)制數(shù)1100,從右邊數(shù)起第三位是處于最右邊的一個(gè)1。減去1后,第三位變成0,它后面的兩位0變成了1,而前面的1保持不變,因此得到的結(jié)果是1011.我們發(fā)現(xiàn)減1的結(jié)果是把最右邊的一個(gè)1開(kāi)始的所有位都取反了。這個(gè)時(shí)候如果我們?cè)侔言瓉?lái)的整數(shù)和減去1之后的結(jié)果做與運(yùn)算,從原來(lái)整數(shù)最右邊一個(gè)1那一位開(kāi)始所有位都會(huì)變成0。如1100&1011=1000.也就是說(shuō),把一個(gè)整數(shù)減去1,再和原整數(shù)做與運(yùn)算,會(huì)把該整數(shù)最右邊一個(gè)1變成0.那么一個(gè)整數(shù)的二進(jìn)制有多少個(gè)1,就可以進(jìn)行多少次這樣的操作。

代碼實(shí)現(xiàn):

c++

class Solution { public:int NumberOf1(int n) {int count = 0;while (n != 0) {++count;n = (n - 1) & n;}return count; } }; class Solution { public:int NumberOf1(int n) {int count = 0;if(n < 0){n = n & 0x7fffffff; //當(dāng)n為負(fù)數(shù)的時(shí)候,只需要將最高位的0置位為1++count; }while( n!=0 ){if(n & 1 == 1){count++;}n = n >> 1;}return count; } };

python

#查找一個(gè)數(shù)二進(jìn)制表示中1的個(gè)數(shù) def NumberOf1(n):count = 0if n < 0 :n = n & 0xfffffffcount += 1while n != 0:if n & 1 == 1:count += 1n = n >> 1return countNumberOf1(3)

總結(jié)

以上是生活随笔為你收集整理的剑指offer(刷题1-10)--c++,Python版本的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。