zoukankan      html  css  js  c++  java
  • 504. Base 7(LeetCode)

    • Total Accepted: 12212
    • Total Submissions: 26829
    • Difficulty: Easy
    • Contributors:satyapriya

    Given an integer, return its base 7 string representation.

    Example 1:

    Input: 100
    Output: "202"
    

    Example 2:

    Input: -7
    Output: "-10"
    首先想到的是比较一般的思路:
    class Solution {
    public:
        string convertToBase7(int num) {
            vector<int> vet;
    		int num1;
    		string s="";
    		if(num==0)
    		return s+="0";
    		else
    		if (num < 0)
    		{
    			num1 = -num;
    			while (num1)
    			{
    				vet.push_back(num1 % 7);
    				num1 = num1 / 7;
    			}
    			s = "-";
    			for (int i = vet.size()-1; i >= 0; i--)
    			{
    				s += to_string(vet[i]);
    			}
    		}
    		else
    		{
    			while (num)
    			{
    				vet.push_back(num % 7);
    				num = num / 7;
    			}
    			for (int i = vet.size() - 1; i >= 0; i--)
    			{
    				s += to_string(vet[i]);
    			}
    		}
    		return s;
        }
    };
    

      接下来,就是改进:

    class Solution {
    public:
        string convertToBase7(int num) {
            string result;
            int anum = abs(num);
            while(anum >= 7) {
                result = to_string(anum%7) + result;
                anum /= 7;
            }
            result = to_string(anum) + result;
            
            if(num < 0) {
                result = "-" + result;
            }
            return result;
        }
    };
    

      

  • 相关阅读:
    UI 常用方法总结之--- UITableView
    UITextFiled 通知监听
    ios 本地通知
    AFNetworking 请求头的设置
    UI总结
    gitlab-server环境搭建
    redis 配置文件示例
    搭建spark集群
    kafka集群安装
    zookeeper集群搭建
  • 原文地址:https://www.cnblogs.com/wujufengyun/p/6814329.html
Copyright © 2011-2022 走看看