码迷,mamicode.com
首页 > 其他好文 > 详细

#Leetcode# 1016. Binary String With Substrings Representing 1 To N

时间:2019-04-13 10:50:15      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:for   put   family   font   example   +=   sub   with   tar   

https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/

 

Given a binary string S (a string consisting only of ‘0‘ and ‘1‘s) and a positive integer N, return true if and only if for every integer X from 1 to N, the binary representation of X is a substring of S.

 

Example 1:

Input: S = "0110", N = 3
Output: true

Example 2:

Input: S = "0110", N = 4
Output: false

 

Note:

  1. 1 <= S.length <= 1000
  2. 1 <= N <= 10^9

代码:

class Solution {
public:
    bool queryString(string S, int N) {
        int num;
        int len = S.length();
        
        for(int i = 0; i <= N; i ++) {
            string t = Binary(i);
            if(S.find(t) == -1) return false;
        }
        return true;
    }
    string Binary(int x) {
        string ans = "";
        while(x) {
            ans += x % 2 + ‘0‘;
             x /= 2;
        }
        for(int i = 0; i < ans.size() / 2; i ++) 
            swap(ans[i], ans[ans.size() - i - 1]);
        return ans;
    }
};

  五题打卡

#Leetcode# 1016. Binary String With Substrings Representing 1 To N

标签:for   put   family   font   example   +=   sub   with   tar   

原文地址:https://www.cnblogs.com/zlrrrr/p/10699868.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!