LWC 53:693. Binary Number with Alternating Bits
来源:互联网 发布:拉比 婴儿床 知乎 编辑:程序博客网 时间:2024/06/05 14:55
LWC 53:693. Binary Number with Alternating Bits
传送门:693. Binary Number with Alternating Bits
Problem:
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
Explanation:
The binary representation of 7 is: 111.
Example 3:
Input: 11
Output: False
Explanation:
The binary representation of 11 is: 1011.
Example 4:
Input: 10
Output: True
Explanation:
The binary representation of 10 is: 1010.
思路:
熟悉JAVA接口的知道,Integer类可以直接把数字转为2进制串。
代码如下:
public boolean hasAlternatingBits(int n) { String binary = Integer.toBinaryString(n); char[] cs = binary.toCharArray(); int bit = cs[0] - '0'; for (int i = 1; i < cs.length; ++i) { if (bit == cs[i] - '0') return false; bit = cs[i] - '0'; } return true; }
当然,你也可以自己解析每一位,代码如下:
public boolean hasAlternatingBits(int n) { int bit = n >> 0 & 1; n >>= 1; while (n > 0) { if (bit == (n & 1)) return false; bit = n & 1; n >>= 1; } return true; }
或者合并到一块:
public boolean hasAlternatingBits(int n) { int bit = -1; while (n > 0) { if (bit == (n & 1)) return false; bit = n & 1; n >>= 1; } return true; }
阅读全文
0 0
- LWC 53:693. Binary Number with Alternating Bits
- leetcode 693. Binary Number with Alternating Bits
- 693. Binary Number with Alternating Bits
- 693. Binary Number with Alternating Bits
- leetcode 693. Binary Number with Alternating Bits
- LeetCode-693. Binary Number with Alternating Bits
- 693. Binary Number with Alternating Bits
- 693. Binary Number with Alternating Bits
- 693. Binary Number with Alternating Bits
- LeetCode 693. Binary Number with Alternating Bits
- 693. Binary Number with Alternating Bits
- leetcode 693. Binary Number with Alternating Bits
- Binary Number with Alternating Bits
- python--leetcode693. Binary Number with Alternating Bits
- Binary Number with Alternating Bits(leetcode)
- Binary Number with Alternating Bits问题及解法
- leetcode 693. Binary Number with Alternating Bits(附正则表达式)
- LeetCode 693 Binary Number with Alternating Bits 带有交替位的二进制数
- unit6
- Python 窗体美化,背景图片,字体样式
- POJ
- [HTML] H5移动端知识点总结
- GIT基本概念和用法总结
- LWC 53:693. Binary Number with Alternating Bits
- js正则入门
- [NOIP2017模拟]Ball
- ConfigReader(二)—— MapLoadConfig
- 自用git指令笔记
- linux安装svn服务器(yum方式)
- 一起来学SQL(三)
- pandas使用入门
- Android群英传学习——控件架构与自定义控件