LeetCode C++ 504. Base 7【Math】简单
发布日期:2021-07-01 02:52:17 浏览次数:3 分类:技术文章

本文共 759 字,大约阅读时间需要 2 分钟。

Given an integer, return its base 7 string representation.

Example 1:

Input: 100Output: "202"

Example 2:

Input: -7Output: "-10"

Note: The input will be in range of [-1e7, 1e7] .

题意:给定一个整数,将其转化为 7 进制,并以字符串形式输出。


思路

进制转换。十进制到七进制的转换,很简单的题目,只是需要注意负数的处理。代码如下:

class Solution {
public: string convertToBase7(int num) {
string ans; bool minus = false; if (num < 0) {
num = -num; minus = true; } do {
int t = num % 7; num /= 7; ans.push_back('0' + t); } while (num); if (minus) ans.push_back('-'); reverse(ans.begin(), ans.end()); return ans; }};

效率如下:

执行用时:0 ms, 在所有 C++ 提交中击败了100.00% 的用户内存消耗:6.1 MB, 在所有 C++ 提交中击败了11.93% 的用户

转载地址:https://memcpy0.blog.csdn.net/article/details/108806972 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode C++ 563. Binary Tree Tilt【Tree/DFS】简单
下一篇:LeetCode C++ 106. Construct Binary Tree from Inorder and Postorder Traversal【Tree/分治】中等

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2024年04月15日 01时42分15秒