判断一个数字的二进制形式是不是01交替的. 如5=101,返回True 如7=111,返回False 这道题可以用位运算来实现.看到01交替,就想到移位运算.如果n是01交替的,移位之后进行异或,则得到的数字x各个位都是1.也就是x=n^(n>>1) 剩下的任务就是判断一个数字是否是2的幂减一.也就是((x+1)&x)==0…
给定一个正整数,检查他是否为交替位二进制数:换句话说,就是他的二进制数相邻的两个位数永不相等. 示例 1: 输入: 5 输出: True 解释: 5的二进制数是: 101 示例 2: 输入: 7 输出: False 解释: 7的二进制数是: 111 示例 3: 输入: 11 输出: False 解释: 11的二进制数是: 1011 示例 4: 输入: 10 输出: True 解释: 10的二进制数是: 1010 class Solution { public: bool hasAlternati…
problem 693. Binary Number with Alternating Bits solution1: class Solution { public: bool hasAlternatingBits(int n) { ; ) { /* errr... if(n&1 && bit==1) return false; else if(n&1) bit = 1; if(n&1==0 && bit==0) return false; els…
Question 693. Binary Number with Alternating Bits Solution 思路:输入一个整数,它的二进制01交替出现,遍历其二进制字符串,下一个与上一个不等,返回true,如果有相等的就返回false Java实现: public boolean hasAlternatingBits(int n) { char last = '2'; // 非0非1即可 for (char c : Integer.toBinaryString(n).toCharArr…
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. Example 1: Input: 5 Output: True Explanation: The binary representation of 5 is: 101  Example 2: Input: 7 Output: False E…
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. Example 1: Input: 5 Output: True Explanation: The binary representation of 5 is: 101 Example 2: Input: 7 Output: False Ex…
Description Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. Example Example 1: Input: 5 Output: True Explanation: The binary representation of 5 is: 101 Example 2: Input…
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. Example 1: Input: 5 Output: True Explanation: The binary representation of 5 is: 101 Example 2: Input: 7 Output: False Ex…
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 遍历判断 判断是否是交替模式 位运算 日期 题目地址:https://leetcode.com/problems/binary-number-with-alternating-bits/description/ 题目描述 Given a positive integer, check whether it has alternating bits:…
题目要求 Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. 题目分析及思路 给定一个正整数,判断它的二进制形式是否是01交替出现.如果是则返回True,否则返回False.可以先获得该数的二进制形式,之后利用切片分别获得其奇数位和偶数位的值.若全为1或0,则是满足要求的数. python代码…